Are quotes really required in $_SERVER ?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
guhan
Forum Newbie
Posts: 6
Joined: Thu Jul 10, 2008 4:44 am

Are quotes really required in $_SERVER ?

Post 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?
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Are quotes really required in $_SERVER ?

Post 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.
guhan
Forum Newbie
Posts: 6
Joined: Thu Jul 10, 2008 4:44 am

Re: Are quotes really required in $_SERVER ?

Post by guhan »

Thanks! :-)
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Re: Are quotes really required in $_SERVER ?

Post 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";
guhan
Forum Newbie
Posts: 6
Joined: Thu Jul 10, 2008 4:44 am

Re: Are quotes really required in $_SERVER ?

Post by guhan »

Thanks Jay!
Post Reply