What is PHP_SELF variable?
PHP_SELF is a variable that returns the current script being executed. This variable returns the name and path of the current file (from the root folder). You can use this variable in the action field of the FORM. There are also certain exploits that you need to be aware of. We shall discuss all these points in this article.
We will now see some examples.
echo $_SERVER['PHP_SELF'];
a) Suppose your php file is located at the address:
http://www.yourserver.com/form-submit.php
In this case, PHP_SELF will contain:
"/form-submit.php"
b) Suppose your php file is located at the address:
http://www.yourserver.com/uri/form-submit.php
For this URL, PHP_SELF will be :
"/uri/form-action.php"
Using the PHP_SELF variable in the action field of the form
However, if you provide the name of the file in the action field, in case you happened to rename the file, you need to update the action field as well. Or else your forms will stop working.
Using PHP_SELF variable you can write more generic code which can be used on any page and you do not need to edit the action field.
Consider, you have a file called form-action.php and want to load the same page after the form is submitted. The usual form code will be:
<FORM method="post" action="form-submit.php" >
We can use the PHP_SELF variable instead of “form-submit.php”. The code becomes:
<FORM name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >