September 30, 2012

how to prevent script tags in zend form

Question by Awais Qarni

Hi there I am just testing my own developed application and got a problem. I entered

<script>window.location = "";</script>

in Zend_Form_Element_Text element. I pressed submit and the value is saved. After saving value I redirect the user to listing and when it redirects to listing, script tag executes and it goes to

My form element looks like

 $first_name = new Zend_Form_Element_Text('first_name');
            ->addValidator('StringLength', false, array(2, $metaData['first_name']['LENGTH']))
            ->setDecorators(array('ViewHelper', 'errors'));

I want to know how can I prevent the user to enter such kind of values? Is there any built in validation or any other way?

Answer by vascowhite

Well done for testing your app, many people don’t bother. Don’t worry about storing that string in your database it won’t do any harm and changing it may give you problems with other, valid, entries. As vstm says, escape it when you use it.

However, as you are specifically talking about a ‘First Name’ field there is probably some more validation that you can do, such as rejecting any names with a / in them. I’m not aware of any language that has that as part of a name. If there is, I’d love to know how it’s pronounced. You could probably add . = and some others to that list too, but don’t get too carried away.

You should carefully consider every field in your form with regards to what input you would reasonably expect to receive and validate the input accordingly. Anything that doesn’t pass validation is rejected. A string like '<script>window.location = "";</script>' should certainly never pass validation for a field expecting a person’s name.

Personally, I never filter input. It either passes validation and is accepted, or it doesn’t and is rejected. I can’t make good input out of bad input by filtering it, so it gets rejected and the user is asked to re-enter their data. For example, using a StripTags filter on

<script>window.location = "";</script>

will leave you with

window.location = “”;

which is still not a valid name and should be rejected.

Your validation will never work 100% of the time and that is why you should always escape values received from user input before echoing them out to the browser.

Zend Framework has a raft of validators that you could use and don’t forget the validators and filters that PHP has already available for you. Use them properly and you will greatly reduce the risk of malicious input hurting either your application or, more importantly, your users.

Those validators and filters are there for you to use, but neither PHP nor Zend Framework know what kind of data you are expecting, so it is very important that you read the documentation and learn exactly how they work, how to use them and when to use them.

There is an excellent resource at The Web Application Security Project that every web dev should be forced to read on pain of death.

Validate input and escape output.

Answer by Starx

You can use filters to restrict input from the user. Read about the filters

There is a filter in Zend Framework called Zend_Filter_StripTags which will give you the option to strip all or selected tags. Here is an example from the site itself.

$filter = new Zend_Filter_StripTags();     
print $filter->filter('<B>My content</B>'); 

As result you will get the stripped content ‘My content’.

On your case the following

            ->addFilter('StripTags') //Here a add a filter to strip tags
            ->addValidator('StringLength', false, array(2, $metaData['first_name']['LENGTH']))
            ->setDecorators(array('ViewHelper', 'errors'));

How will I compare a text input if it is empty or not?

Question by eggshot

How will I compare a text input if it is empty or not inside a Jquery statement? Is the code below alright?

      alert("Should Not Be Empty!");

Answer by Starx


    if($('#lastname').val().trim() != "") {
       alert("Should Not Be Empty!");

Also, there is a typo

//   ^   Right here
September 28, 2012

Difference between typing and pasteing in a field

Question by Ferenc Dajka

If I use xss, what’s the difference between typing in ALERT(‘DSSA’);, or just paste it to a search textfield? In a site, typing works, and makes the alert, but if I just paste it, than it doesn’t. To prevent the question, I don’t want to hack any site, I’m just interested in network security.

thanks for the answer

Answer by Starx

I may not have understood the question properly.

Typing triggers keyUp, keyDown and keyPress events on the element. If the codes are programmed to capture them only, then only those events will be captured.

Pasting can be done using keyboards, mouse and browser options. So this depends on which events you are listening too. There is a separate event called onpaste which will ease everything.

What I mean is, lets say my code is written to capture the pasting my pressing “Ctrl” + “v” only, but if mouse and browser options are used to paste on the
element, then it is configured to capture mouse events also, it cannot
be captured.

Why can't I override existing pseudo-elements?

Question by DanMan

I have two CSS rules following each other:

.some td:first-child:before {
    content:url('path/to/image.png')" " ;
.some .other:before {
    content:url('path/to/image2.png')" " ;

Here’s the HTML snippet:

<table class="some">
    <td class="other">Text goes here</td>
    <td>Some more text.</td>

They’re both supposed to be applied to the same table cell. The one without the class is meant as a fallback. But for some reason, it’s always choosing the first rule over the second. I know the 2nd one works, since it will be used if i disable the first one in Firebug.

What am I missing here?

Answer by DanMan

Ok, to put this straight, after some reading, this is the specificity:

  • Id: 100
  • classes: 10
  • pseudo-classes: 10
  • pseudo-elements: 1
  • elements: 1

So that makes the first selector have a specificity of 22, and the 2nd of just 21. Apparently first-child seems to be a pseudo-class and not a pseudo-element.

Finally, adding a td before .other does the trick, since then document order takes precedence.

Answer by Starx

The first rule is more specific than the second one, so in a case when both the selectors are valid, the more specific one overrides other.

Read this article to know how can we overcome such complications of having conflicting styles. To brief them, Here is how specificity are calculated.

|    Type            |   Specific Value   |  Example                          |
|  Inline Style      |   1000             | style="color: #f00;"              |
|  Id                |   100              | #text { color: #f00; }            |
|  Classes           |   10               | .text { color: #f00; }            |
|  Pseudo Classes    |   10               | a:hover { color: #f00; }          |
|  Pseudo Elements   |   10               | a:first-child { color: #f00; }    |
|  Elements (tag)    |   1                | a { color: #f00; }                |

Basically, Class Selectors are more specific than tag selectors.
Lets calculate your specificity

  • For first rule: 31
  • For second rule: 30

SO the first rule wins.

You can increase the specificity of the second rule like

.some tr td.other:before {
    content:url('path/to/image2.png') ;

Its calculate to 33, to override the style first rule.

September 26, 2012

Zend Framework: Page not found

Question by José Carlos

I have developed a web application with Zend Framework which root is but when I call that url I’ve got the next error:

Page not found

Request Parameters:

array (
  'controller' => 'validacion',
  'action' => 'demo31',
  'module' => 'default',

I want that the values of array would be next:

array (
  'controller' => 'index',
  'action' => 'index',
  'module' => 'default',

And my .htaccess is correct.

So, what do I have to do what I want?

Answer by Starx

Zend framework normally operates as per routes. If a particular URL is not reaching your code, then you have to configure routes to do that.

    $router = $front -> getRouter();
    $routePage = new Zend_Controller_Router_Route('/:controller/:action', array(
    /*                                             ^ Things to notice
                                                     Only two parameters are 
                                                     asked from the route */
        'controller' => 'default',
        'action'    => 'index',
        'module'    => 'default' //Predefine the module as `default
    $router -> addRoute('default', $routePage);
September 25, 2012

Should I place a semicolon at the end of my jQuery statement?

Question by Marilou

Possible Duplicate:
Do you recommend using semicolons after every statement in JavaScript?

I have the code like this:

$("#delete_" + row)
   .attr('data-href', '/Admin/' + tab + 's/Delete' + params)
   .attr('title', 'Delete ' + id);

It’s typical of the code I have everywhere in my application. What I notice is that it seems to work with or without a semicolon at the end. Is there any advantage for formatting or any other reason that I should put a semicolon at the end?

Answer by Explosion Pills

Always put the semicolon. Not only is it more cross-browser compatible, it’s easier to minify (removing newlines is part of that).

Answer by Starx

Semicolons, although not required in JavaScript, denote end of statement. So its a good habit of ending a statement with semicolon at the end. Other point, Explosion Pills has already mentioned.

September 23, 2012

Understanding parameter 'e' and e.pageX/e.pageY

Question by user1692159

function smtMouseMove(e){

function smtTipPosition(e){
    var thePosX=e.pageX+20;

    var thePosY=smtMouseCoordsY+20;


If I have this: var thePosX=e.pageX+20; I gat the error that parameter e is undefined. But if I write var thePosX=smtMouseCoordsX+20; everything is ok. What do I miss in here?

Answer by Starx

On your function declaration, you are asking a parameter e to be sent.

function smtTipPosition(e) {}

But, you are not sending the parameter on your execution.

function smtMouseMove(e){
               // ^ Right here, you have to send the parameter 'e' too

Implementing something like this, should fix the problem.

function smtMouseMove(e){

function smtTipPosition(e){
    var thePosX=e.pageX+20;

    var thePosY=smtMouseCoordsY+20;


Generally, e refers to an event object. It has to be initiated or passed on by some event or function. On you case also, function setMouseMove and smtTipPosition both require a event object for its execution.

Lets see a simple example

$("a").click(function(e) {
    //Here `e` will hold the event object of the page, when any `a` on the page will be clicked
    console.log(e.pageX); //Calling this will give the x coordinates of mouse position on the page, when the `a` was clicked

Syntax error on trying to update empty column row values

Question by Woistmeinhandy

I am trying to add a keyword to empty column / row values in my database but I can’t get it to work. I am getting a syntax error.

Here is the code:

$sql[$handle]['sql'] = 
'SELECT IF(char_length('.$field.')>0, '.$field.',''.$replace.'') AS '.$field.' 
FROM '.$table.'')';

Answer by Starx

You have escaped a quote extra on the end.

$sql[$handle]['sql'] = 
'SELECT IF(char_length('.$field.')>0, '.$field.',''.$replace.'') AS '.$field.' 
FROM '.$table.'')';
//              ^ Right here

Next, you have an extra bracket ) at the end [Credit: Registered User]

$sql[$handle]['sql'] = 
'SELECT IF(char_length('.$field.')>0, '.$field.',''.$replace.'') AS '.$field.' 
FROM '.$table.')';
//             ^ Right here

Solution: Remove them and you should get something like this to work:

$sql[$handle]['sql'] = 'SELECT IF(char_length('.$field.')>0, '.$field.',''.$replace.'') AS '.$field.' FROM '.$table;

Understanding the output of this javascript code

Question by iamrohitbanga

Having programmed in C/C++, Java I am finding difficulty understanding the output of the following program.

var foo = function() {}
foo.prototype.out = function() {
var bar = function() {};

var f = new foo();
f.num = 1;
var b = new bar();
b.num = 2;

console.log(this);           // 1
f.out();                     // 2;   // 3; // 4

I see the following output


I have been coding in javascript for a while now and can understanding some of the concepts but not everything is clear to me.

I have a rough understanding.
I feel in the global space this points to the window and hence the first line of output is clear.
For the second line I think since the function out is being invoked on f the value of this in out is f.
For the third one my feeling is that by calling the function with input as b, the value of -this is set to b.
For the fourth one bar is a global object which has no member named ‘num’ in its dictionary.

Is my understanding correct?
Can someone explain the role of ‘this’ and ‘prototype’ in the context of this program? I find the syntax of prototype slightly obscure.
Also in chrome when I press F12 while in gmail window and paste the program in there. The third line of output is undefined and not 2. But in jsfiddle it is two. which seems somewhat creepy. Why is it different?

Answer by Starx

this represents the scope from where the code is executing. In your case, it is the global scope window.

Prototypes in JavaScript are simply an object with properties and methods. You can add members to it and also inherit from it. You can read this article for further information.

Lets break down your code are see this one by one.

  1. f.out();

    This refers too the following object

    var f = new foo();
    f.num = 1; //Here you define a property `num` as 1

    Then when you call f.out() the prototyped function will simple log the num


    Here you directly access the function and pass an object to the function. Thus when the method is executed, this represents the object that is pass instead, so ends up logging its value.


    On this part, the object bar is an empty object var bar = function() {};, thus the function cannot read its num property, so it outputs as undefined

September 22, 2012

mask output of the input field

Question by telexper

is there any way to mask the output of the input field once passed to the next page

Enter Card : 123456789011

after the data has been passed onto the next page
when displayed it should look like this

Card info: ********9011

the first 8 digits was converted to asterisk and
the last 4 digits of the card is visible.

Answer by Rhyono

If you’ve already ensured that the card number is a valid length:

card = "123456789011";
output = "********" + card.substring(card.length-4);

is all you’ll need. Output will now be as you wanted, and although Starx’s answer is dynamic: it’s also overkill.

Answer by Starx

Something like this

var card = "123456789011";
var str = "";

//Create the "*" for exactly 4 digits short
for(var i=1; i <= card.length-4; i++) {
   str += "*";
//Join the asterisk and last 4 characters
ecard = str + card.substr(card.length-4);




Please fill the form - I will response as fast as I can!