PHP: Server Variable ‘PHP_SELF’ is Unsafe

Posted by Jetlogs @ 9:32 am
Category: PHP,Web Development

How many times have you encountered PHP tutorials where it had used the predefined variable $_SERVER['PHP_SELF'] to send the form action to itself? A simple search from google returns about 33,500 results.

It turns out that using $_SERVER['PHP_SELF'] is quite unsafe due to an XSS exploit. What the PHP_SELF variable does is basically return the filename of the executing script. Consider this simple form:

http://test.com/form.php


<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
   <input type="text" name="username" />
   <input type="submit" value="Submit" />
</form>

If you think that this form is safe, you are mistaken. If someone inputs this URL:
http://test.com/form.php”><script>alert(‘XSS’)</script><”

The form’s output will now look like this:


<form method="POST" action="form.php">
<script>alert('XSS')</script><"">
   <input type="text" name="username" />
   <input type="submit" value="Submit" />
</form>

To prevent this type of attack here are some things you can do:

1. minimize the use of $_SERVER['PHP_SELF']
If you know the target of the form action beforehand, don’t be lazy to rely on PHP_SELF.

2. use an HTML filter
If using PHP_SELF is unavoidable, the next thing you can do is use an entity filter. You can use either PHP’s htmlentities() or htmlspecialchars(). Or even better, you can even try to do strip_tags() beforehand:


<form method="POST" action="<?php
echo htmlspecialchars(strip_tags($_SERVER['PHP_SELF']), ENT_QUOTES);
?>">
   <input type="text" name="username" />
   <input type="submit" value="Submit" />
</form>

3 Comments »

3 Comments to “PHP: Server Variable ‘PHP_SELF’ is Unsafe”

  1. Tester
    1

    Have you tested this? I doubt that the URL:
    http://test.com/form.php”>alert(’XSS’)alert(’XSS’)<”‘ wouldn’t exist.
    Also, the PHP is handled by the server and the page compiled(?) to HTML before the browser gets to display it.

  2. Tester
    2

    Argh, the comments form devoured part of my comment.

    In summary, I don’t think this threat is really a threat [anymore].

  3. Soubyovanna
    3

    It’s amazing

RSS Comment Feed Comments RSS |trackback TrackBack URI

Leave a comment

  • Archives

  • Donations

  • Social Bookmarks

  • Jetlogs.org
    Some Rights Reserved 2007
    Creative Commons License