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 ( "/</", "<", $str2 );
$str2 = preg_replace ( "/>/", ">", $str2 );
$str2 = preg_replace ( "/(\r\n|\n|\r)/", $useBR ? "<br />" : " ", $str2 );
$str2 = preg_replace ( "/&/", "&", $str2 );
$str2 = preg_replace ( "/\'/", "'", $str2 );
return preg_replace ( "/\"/", """, $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!