【发布时间】:2018-12-21 22:53:21
【问题描述】:
我有一个搜索,当用户输入关键字时,脚本会在数据库中查找该关键字:
<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 注入和其他攻击?
或者我需要创建一个黑名单?或者检查其他东西?
【问题讨论】:
-
将值绑定到语句这一事实足以防止 SQL 注入 - 其他任何事情都可能是多余的。
-
如果您稍后将
$query输出到浏览器,您可能会对 XSS 注入开放。不相关但title OR description LIKE有效? -
@user3783243,喜欢在搜索输入中插入关键字
$query?title OR description LIKE有事吗? -
title OR description LIKE不像你想象的那样工作。它只是声明title必须存在(不为空,一个真实值),或者description like something。所以......我怀疑结果将是这方面的预期行为。 -
如果您稍后执行
<input type="text" value="<?php echo $query;?>">,您将对 XSS 注入持开放态度,因为"将关闭该属性,然后其余输入将转到 DOM,例如" onclick="alert('injected')".
标签: php mysql sql regex security