A-A+

PHP登录环节防止sql注入的方法浅析

2021年03月04日 我爱编程 暂无评论

这篇文章主要介绍了PHP登录环节防止sql注入的方法,需要的朋友可以参考下

在防止sql注入这些细节出现问题的一般是那些大意的程序员或者是新手程序员,他们由于没有对用户提交过来的数据进行一些必要的过滤,从而导致了给大家测试的时候一下就攻破了你的数据库,下面我们来简单的介绍一个用户登录未进行安全配置可能出现的sql注入方法,下面一起来看看吧。

比如以下一段登录的代码:

  1. if($l = @mysql_connect('localhost''root''123')) or die('数据库连接失败');
  2. mysql_select_db('test');
  3. mysql_set_charset('utf8');
  4. $sql = 'select * from test where username = "$username" and password = "$password"';
  5. $res = mysql_query($sql);
  6. if(mysql_num_rows($res)){
  7. header('Location:./home.php');
  8. }else{
  9. die('输入有误');
  10. }

注意上面的sql语句,存在很大的安全隐患,如果使用以下万能密码和万能用户名,那么可以轻松进入页面:

$sql = 'select * from test where username = "***" and password = "***" or 1 = "1"';

很明显,针对这条sql语句的万能密码是: ***" or 1 = "1

$sql = 'select * from test where username ="***" union select * from users/* and password = "***"';

正斜线* 表示后面的不执行,mysql支持union联合查询,因此直接查询出所有数据; 所以针对这条sql语句的万能用户名是:***" union select * from users/*

但是,此注入只针对代码中的sql语句,如果

$sql = "select * from test where username = $username and password = $password";

上面的注入至少已经不管用了,不过方法是一样的;

在使用PDO之后,sql注入完全可以被避免,而且在这个快速开发的时代,框架横行,已然不用过多考虑sql注入问题了。

下面整理了两个防止sql注册函数

  1. /* 过滤所有GET过来变量 */
  2. foreach ($_GET as $get_key=>$get_var)
  3. {
  4. if (is_numeric($get_var)) {
  5. $get[strtolower($get_key)] = get_int($get_var);
  6. else {
  7. $get[strtolower($get_key)] = get_str($get_var);
  8. }
  9. }
  10. /* 过滤所有POST过来的变量 */
  11. foreach ($_POST as $post_key=>$post_var)
  12. {
  13. if (is_numeric($post_var)) {
  14. $post[strtolower($post_key)] = get_int($post_var);
  15. else {
  16. $post[strtolower($post_key)] = get_str($post_var);
  17. }
  18. }
  19. /* 过滤函数 */
  20. //整型过滤函数
  21. function get_int($number)
  22. {
  23. return intval($number);
  24. }
  25. //字符串型过滤函数
  26. function get_str($string)
  27. {
  28. if (!get_magic_quotes_gpc()) {
  29. return addslashes($string);
  30. }
  31. return $string;
  32. }

另外还有一些博客会这样写

  1. <?php
  2. function post_check($post)
  3. {
  4. if (!get_magic_quotes_gpc()) // 判断magic_quotes_gpc是否为打开 
  5. {
  6. $post = addslashes($post); // 进行magic_quotes_gpc没有打开的情况对提交数据的过滤 
  7. }
  8. $post = str_replace("_""\_"$post); // 把 '_'过滤掉 
  9. $post = str_replace("%""\%"$post); // 把' % '过滤掉 
  10. $post = nl2br($post); // 回车转换 
  11. $post= htmlspecialchars($post); // html标记转换 
  12. return $post;
  13. }
  14. ?>

给我留言

Copyright © 四季博客 保留所有权利.   Theme  Ality

用户登录