最全PHP防止sql注入方法

(1)mysql_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)自定义函数


  
  
  1. function inject_check($sql_str) {
  2. return eregi('select|insert|and|or|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sql_str);
  3. }
  4. function verify_id($id=null) {
  5. if(!$id) {
  6. exit('没有提交参数!');
  7. } elseif(inject_check($id)) {
  8. exit('提交的参数非法!');
  9. } elseif(!is_numeric($id)) {
  10. exit('提交的参数非法!');
  11. }
  12. $id = intval($id);
  13. return $id;
  14. }
  15.  
  16. function str_check( $str ) {
  17. if(!get_magic_quotes_gpc()) {
  18. $str = addslashes($str); // 进行过滤
  19. }
  20. $str = str_replace("_", "\_", $str);
  21. $str = str_replace("%", "\%", $str);
  22. return $str;
  23. }
  24.  
  25. function post_check($post) {
  26. if(!get_magic_quotes_gpc()) {
  27. $post = addslashes($post);
  28. }
  29. $post = str_replace("_", "\_", $post);
  30. $post = str_replace("%", "\%", $post);
  31. $post = nl2br($post);
  32. $post = htmlspecialchars($post);
  33. return $post;
  34. }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值