PHP: Use htmlspecialchars to output post variables

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In the HTML5 slider control tutorial, we need a form to test the control. The simple way to output what was posted in the form is to do …

The value submitted was <?php  echo $_POST["rating"];  ?>

where “rating” is the name of the form field.  This is WRONG.

You should never use code of that pattern in production code.   That code means that whatever the user inputs in the form will be output directly on your site.  A malicious user can input some HTML and Javascript code (including the <script> tag and it would output directly on your site, running the script.  This is known as Cross-Site Scripting attack (or XSS for short) and is quite common.

It does not matter that the form control can only post integer values.  A malicious users can reproduce your form on their own server and modify it to post anything they like.  And it does not matter that you put in come client-side Javascript of JQuery validation checks on your form.  They can certainly by-pass any type of client-side validation.  Client-side validation is only a convenience check for legitimate users.  It is not meant to be used as a security measure.

Use htmlspecialchars

PHP has a function called htmlspecialchars() which converts certain characters into HTML entities.  Special characters like


are converted to their HTML entities such as


HTML entities are safe to output to the page, because it displays the characters as literals so that browsers do not interpret them as HTML tags.

So in our above example, we should use the following code instead…

The value submitted was <?php  echo htmlspecialchars($_POST["rating"]);  ?>


In page 115 of Build Your Own Database Driven Web Site Using PHP & MySQL, Kevin Yank writes …

“… you should use this function whenever you output a non-HTML text string — especially when you output variables that, as they’re retrieved from a database, or are submitted by users, can have unpredictable values.”