View Full Version : Using quotes correctly in PHP


Stormx
01-07-2006, 10:29 PM
This is one bad habit in PHP which can lead to huge security holes, unexpected results, and people reading your code saying "``` was this guy doing?!"

Consider this script:


<?
$seconds = 5;
echo "You have $seconds seconds remaining!"; //You have 5 seconds remaining!
?>


A lot of people would say "...problem?"

Well yes actually. This behavior is not helpfull in the slightest! Consider:


<?
$seconds = 5;
echo "You have $secondssecs remaining"; //You have 5secs remaining!
?>


It may work as expected it may not, but it leaves a hole open for someone to add in a variable called "secondssecs" in GET, and hense use variable injection using the stupid register_globals functionality

The Advice

Heres the way it should be done:


<?
$seconds = 5;
echo "You have ".$seconds." seconds remaining!"; //You have 5 seconds remaining!
?>


Long winded? I think not. Now you must consider the benifits of using this method!

You can do calculations and use function all in the middle of an echo statement, for example:


<?
echo "2 add 3 is ".(2+3)."! Current unix timestamp: ".time()."!"; //2 add 3 is 5! Current unix timestamp: <number here>!
?>


I beleive this stupid behavior which so many people rely on is scedualled to be removed in PHP6! many people in the ##php channel complain badly when people come in with a script that fails because of their (mis)use of echo, and other functions.

Have fun, and happy coding.

Side note: Never rely on register globals! Initiate all your variables if its on and your site is safe!