我有一个搜索,当用户键入关键字时,脚本会在数据库中查找该关键字:
<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注入和其他攻击?
或者我需要建立一个黑名单?或者检查其他东西?
1条答案
按热度按时间esyap4oy1#
因为您使用的是参数化查询,所以根本不需要正则表达式。参数化查询和仅包含参数之间的区别在于查询最终的执行方式。例如:
这样,查询将被串联起来,然后纯粹地执行。在本例中,您将用户输入作为参数传递:
它不会直接连接采石场,而是比较参数的值
s
. 确保始终使用参数化查询,因为这是一种很好的做法,而且更安全