If you are going to this much effort... you are doing it wrong.
Here are a few contexts where user input must be handled with care, and the correct way to handle them:
HTML. Anything the user inputs that is sent to the browser is interpreted by said browser as HTML. As such, care must be taken to prevent users from injecting code of their choice. Luckily, it's quite simple.
htmlspecialchars
will escape all the necessary characters to ensure that whatever the user typed is what they get back.1JavaScript. Sometimes you may need to drop a variable from PHP into JavaScript. Whether or not it contains user input, you must be careful that you generate valid JavaScript. Luckily,
json_encode
is practically designed for that. Give it a variable and it will output it in a way that JavaScript will understand flawlessly. Strings will have quotes added and characters within will be suitably escaped.MySQL. Perhaps the most argued over, and yet the easiest one to get right! If (and only if) you are stuck maintaining ancient code, you can use
mysql_real_escape_string
to sanitise your input and prevent SQL injection, but really you should be using PDO's prepared statements feature. Likejson_encode
above, prepared statements just take a variable and do all the hard work for you!PHP. Just... don't use
eval
with user input. Ever. Okay?Bash/Shell. Use of
shell_exec
and related functions with user input is rare, but just in case you happen to need it, be sure to always wrap arguments inescapeshellarg
. This, again, handles automatic quoting of strings and escaping of dangerous characters.
Overall, there are built-in, simple ways to do things based on the context you are in. There is no catch-all solution because the contexts are all different with their different rules. Restricting what a user can type in is bad, especially when it's so easy to allow arbitrary input in a safe manner.
1: Spaces will still be collapsed, just like if you type several spaces in the source code. This can be left as desired behaviour, or fixed with the CSS white-space: pre-wrap;
. Consider also word-wrap: break-word;
to ensure that people don't enter stupidly long words to break your layout.