防止 XSS 攻击并正确编码字符

Prevent XSS Attack and encode correctly characters

我有防止sql注入的功能 是一个优秀的功能,确实起到了防止攻击的作用,但是 开始显示字符问题

这个词是“controle de finanças” 在 var_dump 中,我看到字符串 (31) “controle de finanças

我正在尝试一些方法但失败了 2 天请帮助我

function Anti_Sql_Injection($string){ 
        if(ini_get('magic_quotes_gpc') == 'off'){ 
           $string = addslashes($string); 
        }  

        $string = htmlentities($string, ENT_QUOTES);
        $codes = array("script","java","applet","iframe","meta","object","html","CONCAT","CHAR","FLOOR","RAND", "<", ">", ";", "'","%");

        $string = str_replace($codes,"",$string);

        return $string; 
}

试试这个;

function Anti_Sql_Injection($string){
    if(ini_get('magic_quotes_gpc') == 'off') {
        $string = addslashes($string);
    }

    $string = htmlspecialchars($string, ENT_QUOTES,"UTF-8");
    $codes = array("script","java","applet","iframe","meta","object","html","CONCAT","CHAR","FLOOR","RAND", "<", ">", ";", "'","%");

    $string = str_replace($codes,"",$string);

    return $string;
}

我还想向您介绍 PDO. It has built-in SQL injection via prepared statements. Check out this 开始使用 PDO 的教程。我知道它有点旧但仍然有效并且解释得很好。

为什么要使用名为 Anti_Sql_Injection() 的函数来防止 XSS 攻击? You should be using Prepared Statements to stop SQL injection and an appropriate, separate strategy for stopping XSS attacks.

不要一箭双雕。你最终改变了数据。

XSS 预防变得简单

  • 您使用的框架是否提供上下文相关的 XSS 转义?
    • 是:然后使用该功能。将 autoescape 块优先于手动转义过滤器(例如使用 Twig)。
    • 否:是否需要让用户提供一些HTML?
      • 是:HTML Purifier
      • 否:htmlspecialchars($string, ENT_QUOTES | ENT_HTML5, 'UTF-8');

SQL 预防注入变得简单

使用准备好的语句。像 EasyDB 这样的库(包装 PDO)可以减少迁移的痛苦。