首页 > 解决方案 > 如何将htmlentities插入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; 

标签: phpmysqlmysqlixss

解决方案


正确的答案是你不应该这样做。不要将结果存储htmlentities()在数据库中。此函数仅在您在 HTML上下文中输出时使用!您无法确定存储在数据库中的数据是否将始终在 HTML 上下文中使用。
XSS 预防非常依赖于上下文。如果您想输出到 JavaScript 或 CSV 或只是搜索数据库中的值怎么办?如果它们被编码为 HTML 输出,你就不能这样做。

为了回答您更紧迫的问题,我需要提到您的代码容易受到 SQL 注入的影响。使用带有参数绑定的准备好的语句。

正确的 mysqliINSERT查询示例如下:

<?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>';

推荐阅读