javascriptphpjsrenderhtmlspecialchars

pdo fetchAll with htmlspecialchars - protect js injection


So my website will allow users to save <script>alert("hey");</script> to basically any field, and then when I render it, it'll display the alert, and it shouldn't. In reading about it, it sounds like you should use htmlspecialchars when you select and render the data.

I have an api layer where I select the data and return json, which then gets rendered with jsrender.

Here is an example of my query and api:

$return = ["list",[]];
$sql = "SELECT * FROM `News`;"
if ($stmt = $GLOBALS['mysqli']->prepare($sql)) {
        if ($stmt->execute($param)) {
            $list = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $return["list"] = $list ;
        }
}

header('Content-Type: application/json');
echo json_encode( $return);

My templates look something like:

<div class="card-header  py-1 px-2">
        {{:Comment}}
</div>

In my api, where would I put htmlspecialchars?


Solution

  • It should be encoded at the place immediately before it gets rendered into HTML, and since you are not rendering it in PHP but actually in JavaScript, you should do it there (consistently).

    (If you instead encoded it PHP-side, you would have to remember that this text is only intended for display, otherwise you'd end up with double-encoding as soon as you, for example, pass it to another API method.)

    In JSRender there is the {{>...}} tag for that (instead of {{:...}}). For details, see its docs.

    <div class="card-header  py-1 px-2">
            {{>Comment}}
    </div>