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 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止