I've seen $_SERVER['PHP_SELF'] used many times ; in the action of a form.
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
The thing is that you can just as well use action="signup" and this will send the form to that same page without any problem (if we're at example.com/signup ).
<form method="post" action="signup.php" >
My question is why it is almost always done the first way and which one should be used.
You can use either one, but you should know that if you use it
$_SERVER['PHP_SELF']
without any precautions, you can very easily have an XSS attack.In fact, you should not use any variable
$_SERVER
, any superglobal to display it on the screen without properly escaping it.Let's see a simple example of XSS attack if you use
$_SERVER['PHP_SELF']
innocently.Suppose this form:
A normal user will use it as it should, typing in the browser for example:
There no problem. But not everything is rosy and there are some individuals who are called hackers and are not satisfied with clicking on a link to see a nice form. They are going to manipulate the URL, putting for example:
When the hacker types that in the URL, the following code will be produced on the server:
Well... it's not that serious, they just injected you with a simple alert that it will show
xss
in a dialog box that looks even pretty... The problem is that the hacker will later inject you with something much more serious. When the door is open, anything can get in, that's the problem.So
PHP_SELF
is evil?No, evil is the one who has used it irresponsibly. All superglobals that are to be displayed on the screen must be escaped .
This usage is safe:
When pepito the hacker tries his hoax, this will happen:
Conclusions
PHP_SELF
it is safe if used well. But I'm wondering if it's worth using it at all, what's the difference between that and typing the file name? The use ofPHP_SELF
would seem to be a matter of convenience, to write generic code. Maybe it makes sense in an app with thousands or millions of forms? I would say that not even in that case, because there are thousands of strategies to dealaction
with forms, even if they are thousands.Furthermore, thinking about tools like Ajax, we can say that, in a self-respecting application, those pages that are reloaded to send the data to the server are already part of prehistory and are bound to disappear. Nowadays you can program all your forms without
action
or, with the indicated action in a safe way, and use Ajax to send the data to the server. In that case, the file that will be executed when submitting the form will be something else, not the actual file that contains the form. Not only are risks reduced, but it is a super practical, elegant code that saves enormous resources.If you have no choice but to keep writing prehistoric code, a better alternative would be to use
$_SERVER['SCRIPT_NAME']
.Links