gpt4 book ai didi

php - 使用 Twig 生成纯 JSON 响应是否合适?

转载 作者:可可西里 更新时间:2023-11-01 13:01:05 27 4
gpt4 key购买 nike

我正在尝试获取 Eloquent 查询的结果,并将其结果输出为 JSON 响应。我的应用程序使用 Slim 和 Twig 生成 HTML 响应,但是我不确定我是否也应该使用 Twig 生成 JSON。

我知道我可以使用 PHP 的原生 echo json_encode(...) 函数,但是如果我的数据库包含 HTML 实体,这会产生潜在的 XSS 漏洞。 Twig 应该负责适本地转义我的输出。

我知道 this question ,但是它似乎没有提供相关的答案。我也知道 json_encode 过滤器,但是当我这样做时:

/api/users-json.twig

{
"rows" : {{rows | json_encode}}
}

/api/users Controller :

// Simulate database query results
$result = [
"rows" => [
[
"user_name" => "alex",
"message" => "grawr!"
],
[
"user_name" => "h4xx0r",
"message" => "<script>alert('hello, I can execute JS on your website!');</script>"
]
]
];

$app->response->headers->set('Content-Type', 'application/json; charset=utf-8');
$app->render("api/users-json.twig", $result);

响应看起来像:

{
"rows" : [{&quot;user_name&quot;:&quot;alex&quot;,&quot;message&quot;:&quot;grawr!&quot;},{&quot;user_name&quot;:&quot;h4xx0r&quot;,&quot;message&quot;:&quot;&lt;script&gt;alert(&#039;hello, I can execute JS on your website!&#039;);&lt;\/script&gt;&quot;}]
}

如果不进行进一步处理,这在客户端是不可解释的。根据我的浏览器,内容类型正确设置为 application/json

我当然可以:/api/users-json.twig

{
"rows" : {{rows | json_encode | raw}}
}

这给了我回应:

{
"rows" : [{"user_name":"alex","message":"grawr!"},{"user_name":"h4xx0r","message":"<script>alert('hello, I can execute JS on your website!');<\/script>"}]
}

但如果我要在客户端代码中呈现 h4xx0r 的消息,我就会面临 XSS 攻击。

我认为“正确”的输出是:

{
"rows" : [{"user_name":"alex","message":"grawr!"},{"user_name":"h4xx0r","message":"&lt;script&gt;alert(&#039;hello, I can execute JS on your website!&#039;);&lt;\/script&gt;"}]
}

请注意,h4xx0r 的“消息”现在已转义,但整个响应的结构仍保留为有效的 JSON。

当然,我可以遍历每一行并手动 htmlspecialchars 每个值,然后 echo json_encode 或将其传递给 Twig。但这似乎应该是 Twig 的责任!

编辑:看起来 PHP 的 filter_var_arrayjson_encode 相结合,是使用 Twig 的合理替代方案:

$app->response->headers->set('Content-Type', 'application/json; charset=utf-8');
echo json_encode(filter_var_array($result, FILTER_SANITIZE_SPECIAL_CHARS));

产生:

{"rows":[{"user_name":"alex","message":"grawr!"},{"user_name":"h4xx0r","message":"&#60;script&#62;alert(&#39;hello, I can execute JS on your website!&#39;);&#60;\/script&#62;"}]}

但我仍然不确定这是否“应该”用 Twig 代替。

有没有办法用 Slim 和 Twig 做到这一点?或者,我是否完全走错了路,我的客户端 (JS) 代码是否应该负责在呈现之前正确转义内容?

最佳答案

Twig 会将任何给定的变量呈现为 html 编码。然而,当您想要对结果进行 json 编码时,您需要自己遍历数据,因为 Twig 不会为您深入研究数组。

关于php - 使用 Twig 生成纯 JSON 响应是否合适?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32812192/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com