[英]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.