Best way to defend against mysql injection and cross site scripting
Just doing a lot of stuff that you don't really understand, is not going to help you. You need to understand what injection attacks are and exactly how and where you should do what.
In bullet points:
- Disable magic quotes. They are an inadequate solution, and they confuse matters.
- Never embed strings directly in SQL. Use bound parameters, or escape (using
mysql_real_escape_string
). -
Don't unescape (eg.
stripslashes
) when you retrieve data from the database. - When you embed strings in html (Eg. when you
echo
), you should default to escape the string (Usinghtmlentities
withENT_QUOTES
). - If you need to embed html-strings in html, you must consider the source of the string. If it's untrusted, you should pipe it through a filter.
strip_tags
is in theory what you should use, but it's flawed; Use HtmlPurifier instead.
See also: What's the best method for sanitizing user input with PHP?
The best way against SQL injection is to bind variables, rather then "injecting" them into string. http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Don’t! Using mysql_real_escape_string
is enough to protect you against SQL injection and the stropslashes
you are doing after makes you vulnerable to SQL injection. If you really want it, put it before as in:
function madSafety($string)
{
$string = stripslashes($string);
$string = strip_tags($string);
$string = mysql_real_escape_string($string);
return $string;
}
stripslashes
is not really useful if you are doing mysql_real_escape_string
.
strip_tags
protects against HTML/XML injection, not SQL.
The important thing to note is that you should escape your strings differently depending on the imediate use you have for it.
When you are doing MYSQL requests use mysql_real_escape_string
. When you are outputing web pages use htmlentities
. To build web links use urlencode
…
As vartec noted, if you can use placeholders by all means do it.