Home >Backend Development >PHP Tutorial >PHP uses str_replace to prevent injection method_PHP tutorial
PHP various filter character functions
/**
* 返回经addslashes处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
function new_addslashes($string) {
if(!is_array($string)) return addslashes($string);
foreach($string as $key => $val) $string[$key] = new_addslashes($val);
return $string;
}
?>
//对请求的字符串进行安全处理
/*
$safestep
0 为不处理,
1 为禁止不安全HTML内容(javascript等),
2 完全禁止HTML内容,并替换部份不安全字符串(如:eval(、union、CONCAT(、--、等)
*/
function StringSafe($str, $safestep=-1){
$safestep = ($safestep > -1) ? $safestep : 1;
if($safestep == 1){
$str = preg_replace("#script:#i", "script:", $str);
$str = preg_replace("#<[/]{0,1}(link|meta|ifr|fra|scr)[^>]*>#isU", '', $str);
$str = preg_replace("#[ ]{1,}#", ' ', $str);
return $str;
}else if($safestep == 2){
$str = addslashes(htmlspecialchars(stripslashes($str)));
$str = preg_replace("#eval#i", 'eval', $str);
$str = preg_replace("#union#i", 'union', $str);
$str = preg_replace("#concat#i", 'concat', $str);
$str = preg_replace("#--#", '--', $str);
$str = preg_replace("#[ ]{1,}#", ' ', $str);
return $str;
}else{
return $str;
}
}
?>
text);
Dynamic code
$text = preg_replace('/|?'.'>/','',$text);