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:
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>