Dangers in using $_SERVER[‘PHP_SELF’]

Unlike our other posts in the blog this one is not a tutorial, but a warning to our less advanced developer readers. Most of the beginner developers use PHP_SELF in forms, like the example below.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<h1>Sanitize your variables!</h1>
Username: <input type="text">
Password: <input type="text">

Some of you might say, yeah…so what`s the big deal. The big deal is that this example is vulnerable to XSS(Cross Site Scripting) attacks. This situation can easily be exploited, by adding

/"><h1>XSS Example</h1><form%20"

to the url.

Don`t be fooled by the simple example, that way attackers can easily inject malicious javascript in the url and use the link to infect other users. The solution for this problem is infact rather simple…Use htmlentities() php function to sanitize $_SERVER[‘PHP_SELF’].

<form action="<?php echo htmlentities($_SERVER['PHP_SELF'], ENT_QUOTES); ?>" >