正则表达式是否足够,或者我需要更多的检查



我有一个搜索来自,当用户键入关键字时,脚本在数据库中查找该关键字:

<form method="GET">
<input type="text" name="q" id="keyword" placeholder="Enter a keyword" > 
<input type="submit" value="Search" >
</form>

提交表格后,我检查以下内容:

//Check is the form is submitted.
if( isset($_GET['q']) ){
//Assign the submitted keyword to a variable.
$query = $_GET['q'];
//Check if the keyword is empty.
if(!empty($query)){
//Check if the keyword matches the pattern.
//The pattern checks that the keyword contains characters from any language and maybe there are spaces between them.
$pattern = "~^p{L}[p{L}p{M}h()]*$~u";
//If the keyword matches the pattern.
if(preg_match($pattern, $query)){
//Fetch data from the Database.
$stmt = $conn->prepare('SELECT * FROM posts WHERE title OR description LIKE  :s LIMIT 5');
$stmt->bindValue(':s', '%' . $query . '%', PDO::PARAM_STR);
$stmt->execute();
$posts = $stmt->fetchAll();
}
}

这些检查是否足以阻止SQL注入和其他攻击?

或者我需要创建一个黑名单?或者检查其他东西?

由于您使用的是参数化查询,因此根本不需要正则表达式。参数化查询和只连接参数之间的区别在于查询最终是如何执行的。例如:

query q = "SELECT * FROM people WHERE people.age =" + userInput;

这样,查询将被连接起来,然后纯执行。在您的情况下,您正在将用户输入作为参数进行传递:

query q = "SELECT * FROM posts WHERE title OR description LIKE  :s LIMIT 5"

它不会直接连接采石场,它将比较参数s的值。确保您始终使用参数化查询,因为这是一种很好的做法,也是一种更安全的方法

相关内容

最新更新