正则表达式是否足够?还是需要更多检查?

时间:2018-07-13 14:12:05

标签: php mysql sql regex security

我从中进行搜索,当用户键入关键字时,脚本将在数据库中查找该关键字:

<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 个答案:

答案 0 :(得分:3)

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

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

这样,查询将被串联,然后纯粹执行。在您的情况下,您要将用户输入作为参数传递:

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

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