Have I covered all bases with security when echo'ing a server variable to the page?
Question
With forms I've always used
<form method="post" action="<?php echo strip_tags($_SERVER['REQUEST_URI']); ?>">
To get my forms to submit to themselves.
I use striptags()
in case someone links to:
http://www.mysite.com/page-with-form.php?bla="><script src="http://www.nasty.com/super-nasty.js"></script><a href="#
Have I covered all bases, to secure from XSS attacks, or should I use a more whitelist approach, say a regex that only allows alphanumerical characters, the forward slash, question mark, equals sign, parenthesis etc?
Thank you!
Solution
Use htmlspecialchars
instead of strip_tags
.
OTHER TIPS
If you want to reference the same schema/host/path a simple action="?" schould suffice. According to http://tools.ietf.org/html/rfc3986#section-4.2
relative-ref = relative-part [ "?" query ] [ "#" fragment ] relative-part = "//" authority path-abempty / path-absolute / path-noscheme / path-empty
it's a valid relative uri.
Have a form submit to itself by sending it to this:
$_SERVER["PHP_SELF"]
That global variable will output the current page. Unless there's a reason you need the entire query string along with it?
EDIT
Since as pointed out by VolkerK in the comments, even PHP_SELF
is vulnerable, you can write your own little variable based off the PHP_SELF
and explode out the rest of the URI that you know is not part of your page. Something like this:
$file_ext = '.php'; //knowing what file extension your URI is
$page_on = $_SERVER["PHP_SELF"]; //grab this page, with all that junk
$page_huh = explode($file_ext, $page_on); //blow it apart based on file ext
$page_on = $page_huh[0].$file_ext; //attach the leg back onto the URI
echo $page_on;
If your striptags()
strips only tags (characters between "<" and ">" including the angle brackets), someone can still inject javascript:
http://www.mysite.com/page-with-form.php?bla=" onsubmit="return function(){ /*nasty code here*/ }()" style="
Better whitelist every possible meta-characters in HTML, Javascript and CSS (i.e. angle brackets, parenthesis, braces, semi-colons, double quote, single quote, etc).
If you want a form to submit to itself, just leave the action empty e.g.
<form action="" method="POST">
...
</form>