【www.gdgbn.com--php函数】

非法字符过滤本文章主要是讲 php 过滤非法字符没讲asp过滤非法字符 的函数但是思想都一样的.

) 过滤影响MySQL正常运行的字符。

当需要把用户输入的内容(有可能包含单引号、双引号 、反斜线、空字元 NUL )代入到mysql的语句 中执行时,应该把APACHE中的magic_quotes_gpc项设成On。

如果APACHE中的此项设成Off时,也可用php的函数addslashes()达到相同的目的,但这两种手段不能同时使用,否则会出现重复替换,出现错误。

样例:

PHP代码
  
if (get_magic_quotes_gpc()) {    
  
    $content=$_POST["content"];    
  
} else {    
  
    $content=addslashes($_POST["content"]);    
  
}    
  
?>   

当然,如果APACHE中的magic_quotes_gpc项为On,但有时又不想转义某项的特殊字符,可以使用stripslashes()去掉其中的 \

2) 过滤影响MSSQL正常运行的字符。

当需要把用户输入的内容(有可能包含单引号)代入到mssql的语句中执行时,应该把APACHE中的magic_quotes_sybase项设成On,此时magic_quotes_gpc项不再生效。

如果APACHE中的此项设成Off时,php中并没有合适的函数达到相同的目的,只能使用字符串替换函数来达到此目的。

样例:

PHP代码
  
$content=str_replace(""",""""$_POST["content"]);    
  
?>   

现在10.218.17.53上的PHP既要访问mysql又要访问mssql,APACHE中的设置不能兼顾两种数据库,所以只对mysql做了相应设置。

2. 应对用户输入包含SQL语句的一个措施。

以下两种SQL写法都比较普遍,但安全程度是不同的,当用户提交的$id="1 and 1=2 union select ..."时第一种就会显示出不该显示的数据,而第二种就相对安全些。

SQL代码
Select * FROM article Where articleid=$id    
Select * FROM article Where articleid="$id"   

3. 防止用户输入的内容因包含html标签或javascript而影响页面的正常显示。

可以用htmlspecialchars()过滤其中的 & " < >

PHP代码
$content = htmlspecialchars($content);   

4. 当页面要显示的内容包含回车换行时,可以使用nl2br()来达到页面上换行的效果。
方法一.
function chkstr($paravalue,$paratype) //过滤非法字符
{
 if($paratype==1)
 {
  $inputstr=str_replace(""","""",$paravalue);
  }
 elseif($paratype==2)
 {
  $inputstr=str_replace(""","",$paravalue);
  }
 return $inputstr;
}
$user1=chkstr($_GET["user"],1);
$user2=chkstr($_GET["user"],2);
//$user=$_GET["user"];
print "方式1-----------------
";
print "$user1
";
print "方式2-----------------
";
print "$user2
";
?>
方法二.


//用法:qstr($str, get_magic_quotes_gpc())
function qstr($string, $magic_quotes=false, $tag=false)
{
  $tag_str = "";
  if ($tag) $tag_str = """;
  if (!$magic_quotes) {
    if (strnatcmp(PHP_VERSION, "4.3.0") >= 0) {
      return $tag_str.mysql_real_escape_string($string).$tag_str;
    }
    $string = str_replace(""", "[url=file://\\]\\"[/url]" , str_replace("\\", "\\\\", str_replace("\0", "[url=]\\\0[/url]", $string)));
    return  $tag_str.$string.$tag_str;
  }
  return $tag_str.str_replace("\\"", """, $string).$tag_str;
}
?>

本文来源:http://www.gdgbn.com/jiaocheng/14934/