[英]How to insert htmlentities into mysql?
我想保護我的網站免受 XSS 攻擊。 為此,我正在使用htmlentites
。 當我嘗試將變量插入 MySQL 時出現錯誤?
$var = htmlentities("<script>alert('hello')</script>");
$conn = mysqli_connect("localhost","root","","xss");
//mysqli_query($conn,"INSERT INTO entities (ent) VALUES('$var')");
if (!mysqli_query($conn,"INSERT INTO entities (ent) VALUES('$var')"))
{
echo("Error description: " . mysqli_error($conn));
}
echo $var;
正確的答案是你不應該這樣做。 不要將htmlentities()
的結果存儲在數據庫中。 此 function 僅在 HTML上下文中的 output 時使用。 您無法確定存儲在數據庫中的數據是否將始終在 HTML 上下文中使用。
XSS 預防非常依賴於上下文。 如果您想從 output 到 JavaScript 或 CSV 或只是在數據庫中搜索值怎么辦? 如果它們是為 HTML output 編碼的,則無法執行此操作。
為了回答您更緊迫的問題,我需要提到您的代碼容易受到 SQL 注入的影響。 使用帶有參數綁定的准備好的語句。
INSERT
查詢的正確 mysqli 示例如下:
<?php
$var = "<script>alert('hello')</script>";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli("localhost", "root", "", "xss");
$conn->set_charset('utf8mb4');
$stmt = $conn->prepare('INSERT INTO entities (ent) VALUES(?)');
$stmt->bind_param('s', $var);
$stmt->execute();
// use htmlentities when in HTML context
echo '<div>'.htmlentities($var).'</div>';
您可以使用 mysqli_real_escape_string() function 在插入數據庫之前清理數據
$var = htmlentities("<script>alert('hello')</script>");
$conn = mysqli_connect("localhost","root","","xss");
// add this line to sanitize the string before inserting into the database
$var = mysqli_real_escape_string($conn, $var);
if (!mysqli_query($conn,"INSERT INTO entities (ent) VALUES('$var')"))
{
echo("Error description: " . mysqli_error($conn));
}
echo $var;
希望這有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.