需要转义多少个字符? [重复]

This question already has an answer here:

I am new in PHP.

I use two ways to escaping string:

method 1. by using replace

function htmlreplace($str, $useBR = false) {
    $str2 = $str;
    $str2 = preg_replace ( "/</", "&lt;", $str2 );
    $str2 = preg_replace ( "/>/", "&gt;", $str2 );
    $str2 = preg_replace ( "/(
|
|)/", $useBR ? "<br />" : " ", $str2 );
    $str2 = preg_replace ( "/&/", "&amp;", $str2 );
    $str2 = preg_replace ( "/\'/", "&#39;", $str2 );
    return preg_replace ( "/\"/", "&#34;", $str2 );
}
$string='some string needs to insert into mysql';
stripslashes(htmlreplace($string));

method 2. After connecting to MySQL

function sanitizeString($var, $DBconnection) {
    $var = strip_tags ( $var );
    $var = htmlentities ( $var );
    $var = stripslashes ( $var );
    return $DBconnection->real_escape_string ( $var );
}
$string='some string needs to insert into mysql';
trim ( sanitizeString ($string) );

From SQL Injection Prevention Cheat Sheet

shows these characters need to escape

NUL, BS, TAB, LF, CR, SUB, %, ', \, _, all other non-alphanumeric characters with ASCII values less than 256

From PHP addslashes

shows addslashes() function will escape these characters: single quote ('), double quote ("), backslash () and NUL (the NULL byte)

As far as I know, escaping is for prevent SQL injection.

So I am curious about how many characters need to be escaped? what are they? Are they all Special Characters in HTML?

As for SQL injection prevent, thanks to Slico, Marc B, and bub help.

Thanks!

</div>

From OWASP take a look at this link:

Primary Defenses:

  • Option #1: Use of Prepared Statements (Parameterized Queries)

  • Option #2: Use of Stored Procedures

  • Option #3: Escaping all User Supplied Input

Additional Defenses:

  • Also Enforce: Least Privilege
  • Also Perform: White List Input Validation