PHP : Which is more efficient in sanitizing $_get variable?
The string $title is expected only to be lowercase alpha-numeric or the symbol "-" .
In this situation which of the following methods is efficient defense against security vulnerability?
$title=$_GET["title"];
$title = strtolower(preg_replace("/[^a-z0-9\-]+/i", "-", $title));
< mysql query using $title goes here >
OR
$title=$_GET["titl开发者_如何学Ce"];
$title = mysql_real_escape_string($title);
< mysql query using $title goes here >
You should do both.
$title = strtolower(preg_replace("/[^a-z0-9\-]+/i", "-", $title));
And then $title = mysql_real_escape_string($title);
It's always a good practice to escape your mysql values, in this case it's not useful to escape it but if in the future the rule for the title changes and you can put any character, maybe you won't remember to change it
Never use your own escaping methods to escape SQL queries; the database servers will do much better job with it.
To answer the question: regexps are generally really slow. I suppose the function call will be much faster.
Also, never rely to input by users.
I would use the mysql_real_escape_string, this will remove most of the mysql injection problems. If the title does not exist (because, for example, somebody is trying to do mysql injection) then no rows will be found and thus, you display a 404 error
A combination of both. You have to remember your regular expression may not be extensive.
You do not sanitize input!
You validate input (i.e. accept it or decline it) and sanitize output (i.e. change it's representation) using a method appropriate to the destination of the data.
Hence:
if (preg_match("/^[a-z0-9\-]+$/i", $_GET['title'])) {
$my_title=mysql_real_escape_string(strtolower($_GET['title']));
$sql=....'$my_title'....
} else {
print "Invalid value for title";
exit;
}
精彩评论