Using htmlspecialchars within Query function

502 views Asked by At

Instead of manually adding the htmlspecialchars function to all outputted data, I've been trying to instead just place it in my query method so all returned data will automatically be processed.

This is my query method:

function query($query, $params=NULL) {
    $stmt = $this->pdo->prepare($query); 
    $execute = $stmt->execute($params);
    if($execute == false) {
        return false;
    }
    //return $stmt->fetchAll();
    $all_data = array();
    foreach($stmt->fetchAll() as $value) {
        $all_data[] = array_map("htmlspecialchars", $value);
    }
    return $all_data;
}

For some reason, this only seems to work part of the time. I don't receive any errors, except just no data is returning.

What would be the best way to format this method to properly escape all data being outputted?

1

There are 1 answers

0
Scott Arciszewski On

Instead of manually adding the htmlspecialchars function to all outputted data, I've been trying to instead just place it in my query method so all returned data will automatically be processed.

This is a bad move. Always escape on output, never on input. Aside from the "obvious" security benefit of output escaping over input escaping against an attacker with write access to your database, this allows you to get the original data and write unit tests to ensure it's output correctly.

What would be the best way to format this method to properly escape all data being outputted?

Since you're escaping on input and the original data is lost, there's no way to tell what's going wrong from the description given.

But generally, you want to use htmlentities($string, ENT_HTML5 | ENT_QUOTES, 'UTF-8') (assuming your website uses UTF-8; select your encoding appropriately) instead of a naked htmlspecialchars($string).