首页 > 代码库 > 验证表单中输入的特殊字符

验证表单中输入的特殊字符

1.前台表单通过js过滤掉特殊字符

function stripscript(s) {    var pattern = new RegExp("[`~!@#$^&*()=|{}‘:;‘,\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:”“‘。,、?\"]");    var rs = "";    for (var i = 0; i < s.length; i++) {        rs = rs + s.substr(i, 1).replace(pattern, ‘‘);    }    return rs;}var username = stripscript($.trim($(‘#username‘).val()));//对过滤掉特殊字符的字符串进行进一步判断if(username ==‘‘){    error += ‘收货人不能为空\n‘;        is_error = 1;}if(is_error > 0){        alert(error);          return ;}else{        $("form").submit();}    

2.后台代码对特殊字符进行转化

 1 $params = $_GET; 2 foreach($params as $k => $v){ 3         $params[$k] = clean($v); 4 } 5 --将数据存入数据库(省略) 6 public function clean($str) 7 { 8     return addslashes(xssClean($str)); 9 }10 11 //去掉js和html12 static private function _xssClean($str)13 {14      $_search = array(15         "‘<script[^>]*?>.*?</script>‘si",              // 去掉 javascript16         "‘<[\/\!]*?[^<>]*?>‘si",                      // 去掉 HTML 标记17         "‘([\r\n])[\s]+‘",                            // 去掉空白字符18         "‘&(quot|#34);‘i",                            // 替换 HTML 实体19         "‘&(amp|#38);‘i",20         "‘&(lt|#60);‘i",21         "‘&(gt|#62);‘i",22         "‘&(nbsp|#160);‘i"23     ); 24     $_replace = array(                // 作为 PHP 代码运行25         ‘‘,26         ‘‘,27         "\\1",28         "\"",29         "&",30         "<",31         ">",32         ‘‘33     );34     $str = trim($str);35     if (strlen($str) <= 0)36         return $str;37     return @preg_replace_callback($_search, $_replace, $str);38 }

 

验证表单中输入的特殊字符