php - 正则表达式是否足够或我需要更多检查?
问题描述
我有一个搜索,当用户键入关键字时,脚本在数据库中查找该关键字:
<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
。确保始终使用参数化查询,因为这是一种很好的做法,而且更安全
推荐阅读
- oauth - Flutter 中的 oAuth
- postgresql - SQL - 为“不匹配”记录生成计数
- ios - 如果连接到 API Server,则无法跟踪状态
- java - 当我准备在 Eclipse 上为 EGit 做贡献时出现问题,我无法完成下载过程
- javascript - 如何在 react.js 中使用 onClick?
- python - 我可以使用“import tensorflow as tf”将 Tensorflow 导入到 Raspberry pi 3 B+ GPIO 吗?
- ruby-on-rails - 动态表对我的用例有意义吗?数据库/模型架构
- javascript - 未捕获的 TypeError:从 Vue 中的数据调用方法时不是函数
- economics - Gretl-如何创建一个虚拟变量来表示个人有一个小孩
- javascript - 在 Bootstrap 4 中修复页脚?