Page 1 of 1

Are quotes really required in $_SERVER ?

Posted: Fri Jul 11, 2008 5:13 am
by guhan
PHP manual lists the usage of PHP_SELF in $_SERVER with single quotes.. ie.

Code: Select all

$_SERVER['PHP_SELF']
But when I use it in the following way:

Code: Select all

 header("Location: $_SERVER['PHP_SELF']") ; 
I get the following error:
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/.../index.php on line 19 (which is the above line)

And removing the quote works fine. Escaping the quotes with '\' also doesnt work.
As a side note, the following usage also seems to work (and so does the one with quotes around PHP_SELF)....

Code: Select all

<form action="<?php echo $_SERVER[PHP_SELF]; ?>?p=login" method="post"> 
So, my question is:
Are quotes really required when using $_SERVER?
How about in the case of other reserved variables?

Re: Are quotes really required in $_SERVER ?

Posted: Fri Jul 11, 2008 5:52 am
by onion2k
Always use quotes. When you don't use them PHP is taking $_SERVER[PHP_SELF] and assuming PHP_SELF is a constant, looking it up in the table of constants, finding it's missing, and assuming you mean PHP_SELF instead. That's horrible coding because you're relying on PHP's assumption.
Use this instead:

Code: Select all

header("Location: ".$_SERVER['PHP_SELF']) ;
$_SERVER['PHP_SELF'] is outside of the double quoted string so it'll parse properly.

Re: Are quotes really required in $_SERVER ?

Posted: Fri Jul 11, 2008 6:06 am
by guhan
Thanks! :-)

Re: Are quotes really required in $_SERVER ?

Posted: Fri Jul 11, 2008 6:18 am
by jayshields
Alternatively, if you want to parse array variables inside double quotes you can surround the variable with curly braces.

Code: Select all

echo "Blah blah blah {$_SERVER['PHP_SELF']} blah blah";

Re: Are quotes really required in $_SERVER ?

Posted: Fri Jul 11, 2008 7:16 am
by guhan
Thanks Jay!