[英]htmlspecialchars breaks json_decode
To prevent XSS attack, i have used below code. 为了防止XSS攻击,我使用了以下代码。
/* To prevent XSS Attack */
public function __construct($id,$module=null) {
$_GET = $this->clean($_GET);
$_POST = $this->clean($_POST);
$_REQUEST = $this->clean($_REQUEST);
//Call parent constuct
parent::__construct($id,$module=null);
}
/* To prevent XSS Attack */
protected function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
It will clean every get, post requests. 它将清理每个获取,发布请求。 It's working fine.
一切正常。
But now it creates the problem, in code there is lots of place where i am using json_decode. 但是现在它产生了问题,在代码中,我在使用json_decode的地方很多。
example: in one place i have a json_encoded post variable, to decode it i have to use below code: 示例:在一个地方,我有一个json_encoded帖子变量,要对其进行解码,我必须使用以下代码:
$objclass->fields = json_decode(html_entity_decode($_POST['fields'], ENT_QUOTES, 'UTF-8'),true);
If i simply use json_decode($_POST['fields'],true);
如果我只是使用
json_decode($_POST['fields'],true);
then it will fail because $_POST['fields']
data is encrypted using htmlspecialchars. 那么它将失败,因为
$_POST['fields']
数据是使用htmlspecialchars加密的。
So is there a way to so json_decode
will work directly without having to implement html_entity_decode
? 那么有没有一种方法可以使
json_decode
直接工作而无需实现html_entity_decode
?
No, there is no way. 不,没有办法。 If you apply
htmlspecialchars()
to all request data, you'll have to use html_entity_decode()
to get it back in the raw form. 如果将
htmlspecialchars()
应用于所有请求数据,则必须使用html_entity_decode()
才能将其以原始格式重新获得。
This technique is bad in the same way magic quotes were bad. 这种技术很糟糕,就像魔术引号不好一样。 I recommend against using it.
我建议不要使用它。 Instead, use a templating engine and escape the individual variables when needed.
而是使用模板引擎,并在需要时转义各个变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.