, i’m trying to prevent SQL Injection
, is my function enough when I’m using MySQL? How can I improve it?
Thanks for your time and patience.
<?php
function sanitize($data) {
if (is_array($data)) {
foreach($data as $var=>$val) {
$output[$var] = sanitize($val);
}
}
else {
if (get_magic_quotes_gpc()) {
$data = stripslashes($data);
}
$data = htmlspecialchars($data);
$output = mysql_real_escape_string($data);
}
return $output;
}
?>
It is perfect example of what you should never ever use in your code. The rules are very simple:
a) Use prepared statements (I highly recommend this solution)
or (if for some reason you cannot use PDO or mysqli)
b.1) Every (even the one you got from “trusted” source, without any exceptions) string that acts as a value should be
mysql_real_escape_stringedb.2) every integer should be
(int)edb.3) every number that is not integer should be checked if it is what it is expected
b.4) never use user’s input as a substitution for column/table names, always use whitelists
As simple as 1-2-3
So you apply the sanitizing function only when you need it – you never apply some “universal” function to all variables you have
The only way to improve it – is to delete it
UPD:
What is whitelist – let’s say you accept user input to use as a column name. For example for sorting facilities.
So you need to create
array('col1', 'col2')and check if user’s input presents in this array (so called whitelist). If it does – you can use it, otherwise – you wouldn’t do that