Sarathlal N

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, 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:'xss')%3C/script%3E%3Cfoo%22

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. Solve "ValueError invalid literal for int() with base 10" - Python
  2. Handling dynamic subdomain with Flask - Python
  3. A minimal example about WordPress object cache
  4. Select random element from a list - Python
  5. Write our first Selenium program with Python 3 & Firefox

Your Questions / Comments

If you found this article interesting, found errors, or just want to discuss about it, please get in touch.