PHP: Use htmlspecialchars to output post variables
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.
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.”