When we use
PHP_SELF variable to point our current file in form action, we also open a door for hackers. They can easily add some script by type it in the end of our URL & then they can run that script on our page.
Through this post, we are digging deeper about this exploits and method to avoid them in feature.
Consider that we have a page,
welcome.php in our root folder and it have a form that utilize
PHP_SELF variable for form action.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Now, if a user has entered the normal URL in the address bar like
http://www.yourdomain.com/welcome.php, the above code will be translated as
<form action="welcome.php" method="post">.
This is a normal case. But if any one tries to call a script by entering some additional code with our URL in the browser’s address bar like:
In this instance, after PHP processing, our form altered like below one.
<form name="test" method="post" action="welcome.php"/> <script>alert('xss')</script><foo"">
This is a basic script & when the user load this page, it display an alert.
But we can avoid this exploit by using the
htmlentities() function in PHP. When we use
PHP_SELF variable, we must try to encode the HTML entities using this htmlentities() function.
So we alter our form like below one to use htmlentities() function.
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
Now the htmlentities() function encodes the HTML entities. if a user tries to add some code in our URL, the HTML elements in these code are sanitized with htmlentities() function. The result of entering malicious code in URL after PHP processing will become below one.
<form method="post" action="welcome.php/"><script>alert('xss')</script><foo">
Have you get the logic? If so read some extra notes about
PHP_SELF exploits from the web & always remember to use
htmlentities() function in your self submitted forms.