PHP最全防止sql注入方法

1mysql_real_escape_string -- 转义 SQL 语句中使用的字符串中的特殊字符,并考虑到连接的当前字符集 

使用方法如下:

 

  1. $sql = "select count(*) as ctr from users where username
  2. ='".mysql_real_escape_string($username)."' and
  3. password='". mysql_real_escape_string($pw)."' limit 1";

     

       

    使用 mysql_real_escape_string() 作为用户输入的包装器,就可以避免用户输入中的任何恶意 SQL 注入。

    2 打开magic_quotes_gpc来防止SQL注入

    php.ini中有一个设置:magic_quotes_gpc = Off
      这个默认是关闭的,如果它打开后将自动把用户提交对sql的查询进行转换,
      比如把 ' 转为 \'等,对于防止sql注射有重大作用。

         如果magic_quotes_gpc=Off,则使用addslashes()函数

    3)自定义函数

       

     

  4. function inject_check($sql_str) {
  5. return eregi('select|insert|and|or|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sql_str);
  6. }
  7.  
  8. function verify_id($id=null) {
  9. if(!$id) {
  10. exit('没有提交参数!');
  11. } elseif(inject_check($id)) {
  12. exit('提交的参数非法!');
  13. } elseif(!is_numeric($id)) {
  14. exit('提交的参数非法!');
  15. }
  16. $id = intval($id);
  17.  
  18. return $id;
  19. }
  20.  
  21.    
  22. function str_check( $str ) {
  23. if(!get_magic_quotes_gpc()) {
  24. $str = addslashes($str); // 进行过滤
  25. }
  26. $str = str_replace("_", "\_", $str);
  27. $str = str_replace("%", "\%", $str);
  28.  
  29. return $str;
  30. }
  31.  
  32.    
  33. function post_check($post) {
  34. if(!get_magic_quotes_gpc()) {
  35. $post = addslashes($post);
  36. }
  37. $post = str_replace("_", "\_", $post);
  38. $post = str_replace("%", "\%", $post);
  39. $post = nl2br($post);
  40. $post = htmlspecialchars($post);
  41.  
  42. return $post;
  43. }

    转载请注明地址http://www.phpddt.com/php/228.html 尊重他人劳动成果就是尊重自己!

posted @ 2016-01-23 17:50  h4ck0ne  阅读(422)  评论(0编辑  收藏  举报