It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
                            
                        
                    
                
                                7年前关闭。
            
                    
我实质上是在接受用户的输入,将其存储在MySQL数据库中,然后将其输出到同一用户和其他用户。

现在,我将mysql_real_escape_string()应用于用户输入的所有内容,并且每当回显某些内容(然后通过AJAX将其显示给用户)时,我都会应用htmlspecialchars()

这个可以吗?有更好的吗?我想要一个简单,安全的解决方案,以保持文本干净。最好,我也想在文本进入数据库之前对其进行保护,因为一致性在这里对我很重要。

谢谢!

最佳答案

如果您用“安全”一词来表示“干净”,则htmlspecialchars()很好。您可能要使用htmlentities(),它对所有字符进行编码,而不是对特殊字符进行编码。

某些字符由htmlentities()htmlspecialchars()获得(那些字符不在Latin1中),因此,您可能希望“ UTF-8证明”您的输出。您可以使用PHP文档上a comment上找到的此功能。

// Unicode-proof htmlentities.
// Returns 'normal' chars as chars and weirdos as numeric html entites.
function superentities( $str ){
    // get rid of existing entities else double-escape
    $str = html_entity_decode(stripslashes($str),ENT_QUOTES,'UTF-8');
    $ar = preg_split('/(?<!^)(?!$)/u', $str );  // return array of every multi-byte character
    foreach ($ar as $c){
        $o = ord($c);
        if ( (strlen($c) > 1) || /* multi-byte [unicode] */
            ($o <32 || $o > 126) || /* <- control / latin weirdos -> */
            ($o >33 && $o < 40) ||/* quotes + ambersand */
            ($o >59 && $o < 63) /* html */
        ) {
            // convert to numeric entity
            $c = mb_encode_numericentity($c,array (0x0, 0xffff, 0, 0xffff), 'UTF-8');
        }
        $str2 .= $c;
    }
    return $str2;
}


至于在数据进入数据库时​​转义数据,可以在插入数据库之前应用htmlentities。然后,在输出时,可以再次进行适当的测量,但是请确保不要进行双重编码,否则将无法读取任何内容。这是一个例子。

//Decode existing htmlentities
$OutputStringRaw = html_entity_decode(stripslashes($str),ENT_QUOTES,'UTF-8');

//Now you can apply htmlentities (or wtv else) w/o fear of double encoding.
$OutputStringClean = htmlentities($OutputStringRaw);


但实际上,最好只将条目保留在数据库中,而不进行html转义。插入数据时,请使用PDO(在其上为an ok tutorial),或使用一直使用的mysql_real_escape_string继续。

关于php - 最好的PHP安全方法? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11354277/

10-11 23:55
查看更多