繁体   English   中英

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

[英]Is the regular expression enough or I need some more checks?

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

<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注入和其他攻击?

或者我需要创建一个黑名单? 或者检查别的什么?

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM