简体   繁体   English

在查询函数中使用htmlspecialchars

[英]Using htmlspecialchars within Query function

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. 我一直没有尝试将htmlspecialchars函数手动添加到所有输出的数据,而是尝试将其放在我的查询方法中,以便所有返回的数据将被自动处理。

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? 格式化此方法以正确转义所有正在输出的数据的最佳方法是什么?

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. 我一直没有尝试将htmlspecialchars函数手动添加到所有输出的数据,而是尝试将其放在我的查询方法中,以便所有返回的数据将被自动处理。

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) . 但是通常,您要使用htmlentities($string, ENT_HTML5 | ENT_QUOTES, 'UTF-8') (假设您的网站使用UTF-8;请适当选择编码),而不要使用裸露的htmlspecialchars($string)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM