<?php $field = explode(',', $data); array_walk($field, array($this, 'add_special_char')); $data = implode(',', $field); /** * 对字段两边加反引号,以保证数据库安全 * @param $value 数组值 */ public function add_special_char(&$value) { if('*' == $value || false !== strpos($value, '(') || false !== strpos($value, '.') || false !== strpos ( $value, '`')) { //不处理包含* 或者 使用了sql方法。 } else { $value = '`'.trim($value).'`'; } return $value; } function str_filter($str) { $str = htmlspecialchars ( $str ); if (! get_magic_quotes_gpc ()) { $str = addslashes ( $str ); } //过滤危险字符 return preg_replace ( "/[\"\'=]|(and)|(or)|(create)|(update)|(alter)|(delete)|(insert)|(load_file)|(outfile)|(count)|(%20)|(char)/i", "", $str ); } /* 函数名称:str_check() 函数作用:对提交的字符串进行过滤 参 数:$var: 要处理的字符串 返 回 值:返回过滤后的字符串 */ function str_check($str) { if (! get_magic_quotes_gpc ()) { // 判断magic_quotes_gpc是否打开 $str = addslashes ( $str ); // 进行过滤 } $str = str_replace ( "_", "\_", $str ); // 把 '_'过滤掉 $str = str_replace ( "%", "\%", $str ); // 把 '%'过滤掉 return $str; } /* 函数名称:post_check() 函数作用:对提交的编辑内容进行处理 参 数:$post: 要提交的内容 返 回 值:$post: 返回过滤后的内容 */ function post_check($post) { if (! get_magic_quotes_gpc ()) { // 判断magic_quotes_gpc是否为打开 $post = addslashes ( $post ); // 进行magic_quotes_gpc没有打开的情况对提交数据的过滤 } $post = str_replace ( "_", "\_", $post ); // 把 '_'过滤掉 $post = str_replace ( "%", "\%", $post ); // 把 '%'过滤掉 $post = nl2br ( $post ); // 回车转换 $post = htmlspecialchars ( $post ); // html标记转换 return $post; } /* 函数名称:inject_check() 函数作用:检测提交的值是不是含有SQL注射的字符,防止注射,保护服务器安全 参 数:$sql_str: 提交的变量 返 回 值:返回检测结果,ture or false */ function inject_check($sql_str) { return eregi('select|insert|and|or|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sql_str); // 进行过滤 } /* 函数名称:verify_id() 函数作用:校验提交的ID类值是否合法 参 数:$id: 提交的ID值 返 回 值:返回处理后的ID */ function verify_id($id=null) { if (!$id) { exit('没有提交参数!'); } // 是否为空判断 elseif (inject_check($id)) { exit('提交的参数非法!'); } // 注射判断 elseif (!is_numeric($id)) { exit('提交的参数非法!'); } // 数字判断 $id = intval($id); // 整型化 return $id; } // $rptype = 0 表示仅替换 html标记 // $rptype = 1 表示替换 html标记同时去除连续空白字符 // $rptype = 2 表示替换 html标记同时去除所有空白字符 // $rptype = -1 表示仅替换 html危险的标记 function HtmlReplace($str, $rptype = 0) { $str = stripslashes ( $str ); if ($rptype == 0) { $str = htmlspecialchars ( $str ); } else if ($rptype == 1) { $str = htmlspecialchars ( $str ); $str = str_replace ( " ", ' ', $str ); $str = ereg_replace ( "[\r\n\t ]{1,}", ' ', $str ); } else if ($rptype == 2) { $str = htmlspecialchars ( $str ); $str = str_replace ( " ", '', $str ); $str = ereg_replace ( "[\r\n\t ]", '', $str ); } else { $str = ereg_replace ( "[\r\n\t ]{1,}", ' ', $str ); $str = eregi_replace ( 'script', 'script', $str ); $str = eregi_replace ( "<[/]{0,1}(link|meta|ifr|fra)[^>]*>", '', $str ); } return addslashes ( $str ); } //递归ddslashes function daddslashes($string, $force = 0, $strip = FALSE) { if (! get_magic_quotes_gpc () || $force) { if (is_array ( $string )) { foreach ( $string as $key => $val ) { $string [$key] = daddslashes ( $val, $force ); } } else { $string = addslashes ( $strip ? stripslashes ( $string ) : $string ); } } return $string; } //递归stripslashes function dstripslashes($string) { if (is_array ( $string )) { foreach ( $string as $key => $val ) { $string [$key] = $this->dstripslashes ( $val ); } } else { $string = stripslashes ( $string ); } return $string; } /** * 安全过滤函数 * @param $string 要过滤的字符串 * @return string 返回处理过的字符串 */ function safe_replace($string) { $string = str_replace('%20','',$string); $string = str_replace('%27','',$string); $string = str_replace('%2527','',$string); $string = str_replace('*','',$string); $string = str_replace('"','"',$string); $string = str_replace("'",'',$string); $string = str_replace('"','',$string); $string = str_replace(';','',$string); $string = str_replace('<','<',$string); $string = str_replace('>','>',$string); $string = str_replace("{",'',$string); $string = str_replace('}','',$string); return $string; } /** * 使用htmlspecialchars处理字符串或数组 * @param $obj 需要处理的字符串或数组 * @return mixed 返回经htmlspecialchars处理过的字符串或数组 */ function new_htmlspecialchars($string) { if(!is_array($string)) return htmlspecialchars($string); foreach($string as $key => $val) $string[$key] = new_htmlspecialchars($val); return $string; } //处理禁用HTML但允许换行的内容 function TrimMsg($msg) { $msg = trim ( stripslashes ( $msg ) ); $msg = nl2br ( htmlspecialchars ( $msg ) ); $msg = str_replace ( " ", " ", $msg ); return addslashes ( $msg ); }输入 delete from user
<?php define("XH_PARAM_INT",0); define("XH_PARAM_TXT",1); define("DEBUG_MODE",1); //$pi_strName: 变量名 //$pi_Def: 默认值 //$pi_iType: 数据类型。取值为 XH_PARAM_INT, XH_PARAM_TXT, 分别表示数值型和文本型。 function PAPI_GetSafeParam($pi_strName, $pi_Def = "", $pi_iType = XH_PARAM_TXT){ if ( isset($_GET[$pi_strName]) ){ $t_Val = trim($_GET[$pi_strName]); }else if ( isset($_POST[$pi_strName])){ $t_Val = trim($_POST[$pi_strName]); }else{ //如果get post 都没有这个值返回默认值,证明出错 return $pi_Def; } // INT 如果整数直接返回.. //如果应该是数字,输入不是数据直接返回默认值... 0 if ( XH_PARAM_INT == $pi_iType){ if (is_numeric($t_Val)) return $t_Val; else return $pi_Def; } // String $t_Val = str_replace("&", "&",$t_Val); $t_Val = str_replace("<", "<",$t_Val); $t_Val = str_replace(">", ">",$t_Val); //如果打开gpc 再多转一次. if ( get_magic_quotes_gpc() ){ $t_Val = str_replace("\\\"", """,$t_Val); $t_Val = str_replace("\\'", "'",$t_Val); }else{ $t_Val = str_replace("\"", """,$t_Val); $t_Val = str_replace("'", "'",$t_Val); } return $t_Val; } $t_id = PAPI_GetSafeParam("f_id", 0, XH_PARAM_INT); $t_strPwd = PAPI_GetSafeParam("f_pwd", 0, XH_PARAM_INT); if(isset($_POST['f_login'])){ $link = mysql_connect("127.0.0.1",'root','root')or die('数据库连接失败'.mysql_error()); mysql_select_db('books',$link) or die('不能选定数据库'.mysql_error()); mysql_query("set names gbk"); $sql = "select count(*) as count from tb1_user WHERE id={$t_id} and password = '{$t_strPwd}' LIMIT 0,1"; echo '|'.$sql.'|<br />'; if($rs = mysql_query($sql)){ $row = mysql_fetch_assoc($rs); if($row['count'] != 0 ){ echo '登录成功'; }else{ echo '登录失败'; } }else{ if (DEBUG_MODE){ echo '出错原因'.mysql_error(); } } mysql_close($link); } echo str_replace("\\'", "'","ab\'c"); ?>
跨站脚本的过滤RemoveXss函数
function RemoveXSS($val) { // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed // this prevents some character re-spacing such as <java\0script> // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val); // straight replacements, the user should never need these since they're normal characters // this prevents like <IMG SRC=@avascript:alert('XSS')> $search = 'abcdefghijklmnopqrstuvwxyz'; $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $search .= '1234567890!@#$%^&*()'; $search .= '~`";:?+/={}[]-_|\'\\'; for ($i = 0; $i < strlen($search); $i++) { // ;? matches the ;, which is optional // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars // @ @ search for the hex values $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ; // @ @ 0{0,7} matches '0' zero to seven times $val = preg_replace('/(�{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ; } // now the only remaining whitespace attacks are \t, \n, and \r $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base'); $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'); $ra = array_merge($ra1, $ra2); $found = true; // keep replacing as long as the previous round replaced something while ($found == true) { $val_before = $val; for ($i = 0; $i < sizeof($ra); $i++) { $pattern = '/'; for ($j = 0; $j < strlen($ra[$i]); $j++) { if ($j > 0) { $pattern .= '('; $pattern .= '(&#[xX]0{0,8}([9ab]);)'; $pattern .= '|'; $pattern .= '|(�{0,8}([9|10|13]);)'; $pattern .= ')*'; } $pattern .= $ra[$i][$j]; } $pattern .= '/i'; $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags if ($val_before == $val) { // no replacements were made, so exit the loop $found = false; } } } return $val; }