I 'm not sure what exceptions the manual is referring to when talking about making data safe. You could say that the exception is when the data is already known to be safe. For example, here are a few cases that come to mind:
- the data is typed as a number (this is really a specialization of the next item)
- you already know it does not contain any characters that need to be escaped (e.g. it comes from looking up something in a "whitelist" array that contains a few options you hardcoded)
For example, if you have $id = intval($_GET['id'])
then you do not need to escape $id
before injecting it into a query.
However! It can never hurt you to escape all input, and doing so eliminates the chance that you introduce vulnerabilities in your code (e.g. if you forget to escape, if the requirements change, or anything really). So I recommend getting into the habit of escaping everything and forgetting about "exceptions".
As for the %
and _
characters as part of the input, these do not need to be escaped unless you are going to feed this input to a command that recognizes them. So for example, if you have a query like this:
$term = $_GET['term'];
$sql = sprintf("SELECT FROM table WHERE column LIKE '%%s%'",
mysql_real_escape_string($term));
In this case, if the user types a %
as part of $term
it's reasonable to assume that they want to actually search for a literal %
. Therefore in such cases you should escape %
by replacing it with \%
(\
is the default escape character). str_replace
or strtr
are two good options for this.