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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog