$_SERVER['PHP_SELF'] -> usefulness?

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
konstandinos
Forum Commoner
Posts: 68
Joined: Wed Oct 04, 2006 4:20 am

$_SERVER['PHP_SELF'] -> usefulness?

Post by konstandinos »

tutorials insist on using this when assigning the action attribute to a form tag, ie:

Code: Select all

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" etc.
from what i understand, all this does is return the url from the document root up. ie: using the code on http://www.kosta.com/foo/login.php would just give /foo/login.php

but now i ask, what's the point?

using the code below works perfectly fine:

Code: Select all

<form action="login.php"
all i want is to call the same file that the script is in so why all the fancy superglobal code?

i hope this isn't a silly question. my gut thinks it is.
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

actually if you want to return the page to itself, you don't even need the action attribute of the tag. Alternatively (and best practice) you can use #.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

A little safer way (than using $_SERVER['PHP_SELF']) is to use basename($_SERVER['SCRIPT_FILENAME']).

Reasoning for using superglobal page name references varies, but typically it has to do with portability. Generally speaking, if you have a reference to the scripts page name throughout the page, you can set it in the form of a var and use that var throughout the page. Then, if the page name changes, the var automagically changes with it, rather than you having to re-hardcode the page name throughout the script.
Post Reply