BigMac66 BigMac66 - 1 year ago 40
PHP Question

Odd and confusing PHP syntax

I am taking over the maintenance of an old web site and came across this confusing syntax for processing a form that I have never seen before and I am not exactly certain what it does:

foreach (array('address','comments','country','email','mail_content','name','title') as $vuln)
isset($_REQUEST[$vuln]) and $_REQUEST[$vuln] = htmlentities($_REQUEST[$vuln]);
isset($_GET[$vuln]) and $_GET[$vuln] = htmlentities($_GET[$vuln]);
isset($_POST[$vuln]) and $_POST[$vuln] = htmlentities($_POST[$vuln]);
isset($$vuln) and $$vuln = htmlentities($$vuln);

Its the "and" that is throwing me - I read it as "if variable is set convert it to htmlentities. But why is there an "and" in there?

Finally what does the last line do?

isset($$vuln) and $$vuln = htmlentities($$vuln);

Answer Source

It's using the operator precedence rules of PHP in an unusual way.

If you have an and statement, PHP will stop processing it if the left side is false - there's no need to check the right hand side, because it won't make a difference to the end result. (The converse is also true for an if statement if the left hand side is true.)

So the coder that wrote this is using it as a shorthand for:

if (isset($_REQUEST[$vuln])) {
    $_REQUEST[$vuln] = htmlentities($_REQUEST[$vuln]);

They've save a small amount of typing, at the cost of making the code slightly harder to read. It's good practice to use isset to make sure that your array values are set before you use them, which is why the check is there.

As to the last line; logically, it's doing the same as the above, but with a variable variable. The first time through, $vuln will be set to the first item in your array, which is address - the final line of code is checking to see if there's a variable called $address, and if so, set its value to htmlentities($address).

That's what the code is doing. Why it's checking REQUEST, GET, and POST is beyond me.