Okay, so there's all these different string-escaping functions such as htmlentities()
, mysql_real_escape_string()
, addslashes()
But which should I use in what situation?
Resources and opinions please :)
Okay, so there's all these different string-escaping functions such as htmlentities()
, mysql_real_escape_string()
, addslashes()
But which should I use in what situation?
Resources and opinions please :)
<b>Something</b>
to a HTML page, you will just see Something (i.e. the original text in bold) - you won't see the bold tags around it. Using htmlentities('<b>Something</b>')
converts the code to <b>Something<b> so in the browser you see the triangle brackets.In summary:
which should I use in what situation?
htmlspecialchars()
. For printing untrusted user input into browser.when you insert data to a mysql database use this:
mysql_real_escape_string()
when you're going to display content a user gave you:
htmlentities()
if you database doesn't have it's own function in php, you could use:
addslashes()
, but it's not recommended to use when you have something specific that is better (mysql_real_escape_string()).
see this for more info:
Htmlentities vs addslashes vs mysqli_real_escape_string
P.S you should use mysqli_real_escape_string(), not mysql_real_escape_string().
EDIT:
to really prevent attacks, this is good reading material : http://www.php.net/manual/en/security.database.sql-injection.php...
You should also look into prepared statements: http://www.php.net/manual/en/mysqli.prepare.php
a lot of info is also available here on stack overflow.
It's all a variation on the same theme:
$bar = "O'Reilly";
"foo = '$bar'"; // foo = 'O'Reilly' -> invalid syntax
Blindly concatenating strings together may lead to syntax violations if the strings are supposed to follow a special syntax. At best this is an annoyance, at worst a security problem. Escaping values prevents these problems. Generic example:
"foo = '" . escape($bar) . "'"; // foo = 'O\'Reilly'
All the different functions are escaping values properly for different syntaxes:
htmlentities
for escaping output for HTML.
mysql_real_escape_string
for escaping values for SQL queries.
addslashes
… not really good for anything, don't use.
json_encode
for encoding/escaping/converting values for Javascript format.