Understand & avoid PHP_SELF exploits

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"/>

This is a basic script & when the user load this page, it display an alert.

We can add any javascript code like above one and there is too many possibilities for a hacker in such instance. They can redirect our page to another server, they can alter our global variable and can also submit our user’s submitted values to another server.

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/&quot;&gt;&lt;script&gt;alert('xss')&lt;/script&gt;&lt;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.

Recent Posts

  1. Replace string in multiple files - Command line
  2. Solve Grunt error - Port 35729 is already in use by another process
  3. Install WP-CLI
  4. Install LAMP - Apache2 , MariaDB, PHP 7 on Debian 8
  5. Enable / Disable Magento 2 module using command line

Questions / Comments

If you found this article interesting, found errors, or just want to discuss about them, please get in touch. Send an email to hello@sarathlal.com & I like your words.