duanbo5230 2015-03-04 17:20
浏览 62

PHP Web Service将HTML字符作为实体返回

I have a PHP web service which returns data in JSON format. I have a custom backend to maintain the data. When I save a record via the backend I use htmlspecialchars() on string fields.

An example web service call would run this code:

$dbh = getConnection('read');

$sql = "SELECT Name, Location FROM Venues WHERE id = :venueID";
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':venueID' => $venue));
$data = $sth->fetchAll(PDO::FETCH_ASSOC);

header("Content-type: application/json");
print(json_encode(array('venues'=>$data)));

So lets assume that for the provided venue ID the name has a & in it. The web service is called by an Android application so in the application it is displayed as a & and not &

Questions:

  1. Do I tweak the custom backend to not use htmlspecialchars? I am the only admin so the data going in is safe
  2. Is there a way to run htmlspecialchars_decode on the resultset without looping through the results before I print the JSON?
  • 写回答

1条回答 默认 最新

  • dsgfdgh14569 2015-03-04 17:29
    关注

    The real answer here is that you should not be html encoding data that is going into your database. You want the data in your database to be exactly what the user entered.

    An engineer is not expecting data in the database to be escaped in any way. As you can see, doing this forces you to remember to unencode the data whenever you take it out of the database. The problem in your case, is that htmlspecialchars is never meant to be reversed as the browser takes care of that for you in its rendering of the HTML.

    You would normally use HMTL escaping in PHP templates like so:

    <?php
    $db = //get database connection
    $data = $db->read//....
    ?>
    <div>
    <?=htmlspecialchars($data)?>
    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器