最详细的防止sql注入方法详解

jerry mysql 2016年03月12日 收藏

【一、在服务器端配置】
安全,PHP代码编写是一方面,PHP的配置更是非常关键。
我们php手手工安装的,php的默认配置文件在

  1.  /usr/local/apache2/conf/php.ini

,我们最主要就是要配置php.ini中的内容,让我们执行 php能够更安全。整个PHP中的安全设置主要是为了防止phpshell和SQL Injection的攻击,一下我们慢慢探讨。我们先使用任何编辑工具打开 /etc/local/apache2/conf/php.ini,如果你是采用其他方式安装,配置文件可能不在该目录。

(1) 打开php的安全模式
php的安全模式是个非常重要的内嵌的安全机制,能够控制一些php中的函数,比如system(),
同时把很多文件操作函数进行了权限控制,也不允许对某些关键文件的文件,比如/etc/passwd,
但是默认的php.ini是没有打开安全模式的,我们把它打开:

  1. safe_mode = on

(2) 用户组安全
当safe_mode打开时,safe_mode_gid被关闭,那么php脚本能够对文件进行访问,而且相同
组的用户也能够对文件进行访问。

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

使用方法如下:

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

使用

  1. mysql_real_escape_string()

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

(4) 打开magic_quotes_gpc来防止SQL注入

        php.ini中有一个设置:

  1. magic_quotes_gpc = Off

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

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

(5)自定义函数

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