【问题标题】:Echoing Javascript htmlspecialchars from PHP从 PHP 回显 Javascript htmlspecialchars
【发布时间】:2018-10-06 08:21:56
【问题描述】:

我使用 htmlspecialchars 将 javascript 代码(谷歌分析 js 代码)存储在 php 变量中以转义单引号。 问题是当我将 javascript 输出到 html 页面时,javascript 打印为文本

这个来自 setting.php 并将保存到 config.php

$analyticcode = htmlspecialchars("'.$_POST['analytic'].'"); 

config.php

$analyticcode = htmlspecialchars("
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-1111111-1', 'auto');
  ga('send', 'pageview');
</script>");

这是来自 echo 输出的 html

"\r\n&lt;script&gt;\r\n  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\r\n  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\r\n  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\r\n  })(window,document,'script','https:\/\/www.google-analytics.com\/analytics.js','ga');\r\n  ga('create', 'UA-111111-1', 'auto');\r\n  ga('send', 'pageview');\r\n&lt;\/script&gt;"

请告诉我正确的方式来回应这个到 html, 谢谢你

【问题讨论】:

  • 简单不要使用htmlspecialchars

标签: javascript php


【解决方案1】:

不要使用 htmlspecialchars()。但只是一个字符串。

示例源代码:https://hastebin.com/elaloxiqow.xml

示例结果:http://kironweb123.000webhostapp.com/test.php

$analyticcode = "
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-1111111-1', 'auto');
  ga('send', 'pageview');
</script>";

我希望这就是你的意思。

编辑:根据您的代码http://hastebin.com/ukibebijav.xml,如果您在 index.php 中使用它可能会起作用

【讨论】:

  • 它在我的页面上不起作用,我使用 $_POST 从 获取代码,然后将其作为变量保存到 php
  • 你的意思是,的值就是" “?
  • 是的,这个javascript取自文本区域并保存到诸如config php文件中
  • 也许然后代替 htmlspecialchars() 做 htmlspecialchars_decode()?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-30
相关资源
最近更新 更多