I've been trying to make a secure search querying with PHP.
So far, this is my code, which is incorrect:
else if(!ctype_alpha($searchkey) && !is_numeric($searchkey) &&!ctype_print($searchkey)){
$data['errMsg'] = "Please enter a valid search key.";
}
Although ctype_print
is kinda good, it still accepts non-alpha characters, which is unsafe to SQL injections. What can I use that will allow whitespaces but disallow non-alphanumeric characters? Thank you. All answers will be greatly appreciated.
Edit:
So I got it. Sometimes, I get so silly. To keep from getting unsafe inputs, I used PHP's mysql_real_escape_string
. Sorry guys.
use ctype_alnum()
function:
!ctype_alnum($searchkey)
this checks if string is alpha-numeric
preg_match('/[a-zA-Z0-9\s]+/', $searchkey);
Try with:
function coolCheck($string) {
return preg_match("/^[a-zA-Z0-9\s]*$/", $string);
}
If you're trying to defend against SQL Injection I would use a prepared statement (PDO example):
$stmt = $dbh->prepare('SELECT stuff FROM table WHERE input = ?');
$stmt->execute($searchkey);
foreach($stmt as $row){
//do something
}
This is far more effective than any input sanitisation you can create.
If you're just looking to simply format the search query in a particular way please ignore this and use something like ctype_alnum($searchKey)
, PHP manual: http://php.net/manual/en/function.ctype-alnum.php