To be honest, I think the author of these function has either no idea what XSS and SQL injections are or what exactly the used function do.
Just to name two oddities:
Furthermore: In general, functions that protect agains XSS are not suitable to protect agains SQL injections and vice versa. Because each language and context hast its own special characters that need to be taken care of.
My advice is to learn why and how code injection is possible and how to protect against it. Learn the languages you are working with, especially the special characters and how to escape these.
Edit Here’s some (probably weird) example: Imagine you allow your users to input some value that should be used as a path segment in a URI that you use in some JavaScript code in a onclick
attribute value. So the language context looks like this:
And to make it more fun: You are storing this input value in a database.
Now to store this input value correctly into your database, you just need to use a proper encoding for the context you are about to insert that value into your database language (i.e. SQL); the rest does not matter (yet). Since you want to insert it into a SQL string declaration, the contextual special characters are the characters that allow you to change that context. As for string declarations these characters are (especially) the "
, '
, and \
characters that need to be escaped. But as already stated, prepared statements do all that work for you, so use them.
Now that you have the value in your database, we want to output them properly. Here we proceed from the innermost to the outermost context and apply the proper encoding in each context:
- For the URI path segment context we need to escape (at least) all those characters that let us change that context; in this case
/
(leave current path segment), ?
, and #
(both leave URI path context). We can use rawurlencode
for this.
- For the JavaScript string context we need to take care of
"
, '
, and \
. We can use json_encode
for this (if available).
- For the HTML attribute value we need to take care of
&
, "
, '
, and <
. We can use htmlspecialchars
for this.
Now everything together:
'… onclick="'.htmlspecialchars('window.open("http://example.com/'.json_encode(rawurlencode($row['user-input'])).'")').'" …'
Now if $row['user-input']
is "bar/baz"
the output is:
… onclick="window.open("http://example.com/&quot;%22bar%2Fbaz%22&quot;&quot;)" …
But using all these function in these contexts is no overkill. Because although the contexts may have similar special characters, they have different escape sequences. URI has the so called percent encoding, JavaScript has escape sequences like \"
and HTML has character references like "
. And not using just one of these functions will allow to break the context.