PHP escaping inputs and filtering outputs
1I’ve spent more time than probably necessary lately to find the best solution to escaping inputs and filtering outputs from your PHP script. I made the mistake of “over sanitizing” user inputs by first running them through PHP’s filter_var function immediately when capturing the request, then running the data through mysql_real_escape_string(), and then passed it off to PDO, which automatically escapes the bound parameters for you. I ran into problems with special characters, namely single and double quotes because filter_var would convert them to their html_entities or ascii equivalents and store them in the database as such while other data in the application escaped the quotes with a backslash. Rather than go through all the tests I ran, I’ll provide the solution I found that handles inputs best.
- Do not convert quotes or any special characters to their ascii equivalents by using htmlspecialchars() or filter_var($var, FILTER_SANITIZE_STRING)
- Use PDO or mysql_real_scape_string prior to inserting into the database
- When outputting the data, use stripslashes() and htmlentities().
The htmlentities() is important so characters such as a double quote followed by a greater than sign won’t break your html input. If they’re converted to their ascii character, they’ll still print properly and won’t break your html. Also, it’s worth noting that if you enter the value “nick\s” in an input field and save it to the database, the value will be stored as “nick\\s” and when you use stripslashes() on this, only one of the two backslashes will be removed, which is the desired behavior.
Hi I'm Nick Bartlett and thanks for visiting my blog. I'm not much of a writer; many of my posts are short and to the point while others are meant to be a reference for myself and other web developers.
Trackbacks/Pings