【问题标题】:Prevent input to submit html code/script防止输入提交html代码/脚本
【发布时间】:2016-10-08 14:38:34
【问题描述】:

我正在创建一个用户可以发布文章的目录。为了获取要发布的值,我使用输入 html 元素并使用 $.post 将数据保存在数据库中。

但是,我有一个问题,如果用户在文章中编写了一些 html 代码,它会保存格式化代码。

例如,如果输入的值为:

<input type="text" value="this is an article title <script>$("body").remove();</script>">

提交帖子后,页面还将加载删除body的js脚本。

如何避免这种情况并告诉输入字段中有一个脚本,或者将脚本格式化为显示为文本?

【问题讨论】:

  • 你需要清理服务器上的用户输入 - JS/jQuery 不是这项工作的正确工具,因为它太容易绕过了。
  • 我必须在我的 php get 上这样做?
  • 非常感谢它的工作原理 ----- $title = htmlspecialchars(filter_input(INPUT_GET, "title"), ENT_QUOTES);

标签: javascript jquery html input


【解决方案1】:
<?php

//Simple answer
#when you echo data results from the database. consider code below..
#Assuming you are at the last process of echoling the data out.
$data='THIS WOULD BE YOUR DATA OBJECT OR VARIABLE CONTAINING DATA FROM THE DATABASE';


#then...
$data=htmlentities($data);
#or
$data=strip_tags($data);
#or
$data=htmlspecialchars($data);


#just be assured that tags or code will not be executed by the browser once above is included!
echo $data;

【讨论】:

  • 谢谢,但是当我返回数据时,我将其作为 json 返回
  • 然后 json 编码你的数据。比如==> $data=json_encode(htmlspecialchars($data));
猜你喜欢
  • 2020-11-30
  • 2016-02-07
  • 2013-06-20
  • 1970-01-01
  • 2011-03-10
  • 1970-01-01
  • 2016-11-23
  • 2017-12-05
  • 2011-12-19
相关资源
最近更新 更多