避免使用没有htmlspecialchars的引号

时间:2017-09-27 11:18:55

标签: javascript php

我在search.php文件下面:

<?php
$q = $_GET["q"];
?>

<html>
...
<input id="inp" type="text">
...
...
<script>
// here i'm trying to avoid harmful user input with htmlspecialchars        
document.getElementById("inp").value = "<?php echo htmlspecialchars($q); ?>"; 
</script>
...
</html>

当我请求search.php?q = Adam(或任何A-Z,a-z)时它正常工作。但是当我搜索&#34;或\输入值与$ _GET [&#34; q&#34;]值不同。

但如果我搜索&#34;它添加\,见下图。

enter image description here

我需要的是将输入值设置为$ _GET [&#34; q&#34;]。有没有更好的解决方案?

1 个答案:

答案 0 :(得分:4)

// here i'm trying to avoid harmful user input with htmlspecialchars        
document.getElementById("inp").value = "<?php echo htmlspecialchars($q); ?>";

您正在生成 JavaScript ,而不是HTML。

(虽然它嵌入在HTML文档中,但<script>元素被定义为包含CDATA,因此HTML的常规规则不适用。)

将PHP数据结构或基元转换为JavaScript兼容格式的适当工具是json_encode

document.getElementById("inp").value = <?php echo json_encode($q); ?>;
相关问题