I'm trying to sanitize a string to be saved in a db.
First step I took was to use addslashes()
, but then I realized it didn't solve many security issues, so I added htmlspecialchars()
, and now I have this line of code:
$val=htmlspecialchars(addslashes(trim($val)));
But then I was wondering if it makes any sense at all to use addslashes()
on a string that will be processed by htmlspecialchars()
, since the latter will "remove" any element that would cause problems, if I'm not mistaken.
In particular, I was wondering if that makes the server work twice without any real need.
I wouldn't use either of those when saving the string to the database.
addslashes()
escapes only quote characters and the backslash character (\). It's not adequate for avoiding SQL injection, because the DBMS may use other special characters which would have to be escaped as well. The best way to avoid SQL injection is to use PHP data objects and its support for bind parameters, which let you keep the parameter values out of the SQL string entirely. If PDO isn't an option for some reason, you should at least use a database-specific escaping function, e.g. mysqli_real_escape_string
if you're using MySQL, to ensure that all the necessary characters are escaped.htmlspecialchars()
is for use when incorporating a non-HTML string into an HTML page; it escapes characters that are significant to a web browser, such as angle brackets, and has nothing to do with databases. Assuming that you're not generating and storing complete HTML documents in your database, you shouldn't be calling this function on values before putting them into the database. Store what the user actually entered, and call htmlspecialchars()
when you retrieve the value from the database and you're about to actually put it into some HTML output.