Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd and confusing PHP syntax

Tags:

php

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);
}

It's 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);
like image 547
BigMac66 Avatar asked Dec 10 '22 16:12

BigMac66


1 Answers

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 or 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.

like image 83
andrewsi Avatar answered Dec 29 '22 07:12

andrewsi