如何转义 URL 参数以防止 HTML 注入



在代码的最后一行中转义URL参数以防止通过参数化的href url注入HTML的好方法是什么?我的意思是:编辑表单.php?id=' .$row["客户 ID"] .">"部分。

require_once 'common.php';
$stmt = $db->query("SELECT * FROM customers ORDER BY CustomerID DESC");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($results && $stmt->rowCount() > 0) 
{ 
echo '<h2>Results</h2>';
//Here comes some plain HTML for table design.
//Then a FOR loop.
foreach ($results as $row) 
{ 
echo '<tr>';
echo '<td><a href="editform.php?id=' . $row["CustomerID"] . '">' . $row["CustomerID"] . '</a></td>';

我想在公共.php中编写一个函数。像这样:

function escape($html)
{
    return htmlspecialchars($html, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
}

这会是决定性的吗?或者我应该使用类似的东西:filter_var($url、FILTER_SANITIZE_URL(;

我会使用urlencode作为链接,使用htmlspecialchars作为文本。

echo '<td><a href="editform.php?id=' .  urlencode($row["CustomerID"]) . '">' . htmlspecialchars($row["CustomerID"], ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8") . '</a></td>';
对于 URL

的任何组件,您需要对其进行 URL 编码(使用 urlencode (。这将避免 URL 本身出现空格、特殊字符和&的问题。

然后,您需要使用 htmlspecialchars 转义完整的属性值。这同样适用于您在 HTML 中包含的任何文本。

最新更新