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:
http://www.yourdomain.com/welcome.php/%22%3E%3Cscript%3Ealert('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"/>
<script>alert('xss')</script><foo"">
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/"><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.
Got a project in mind? Send me a quick message, and I'll get back to you within 24 hours!.
Recent Posts
- Disabling Payment Methods in WooCommerce Based on Conditions
- How to Update Product Quantity in WooCommerce Using Custom Code
- Dynamically Generating a Table of Contents in WordPress
- Direct Checkout in WooCommerce - Add Product to Cart from Checkout Page & Skip Shop, Product, and Cart Pages
- Understanding the Impact of git reset --hard Command
Your Questions / Comments
If you found this article interesting, found errors, or just want to discuss about it, please get in touch.