php层防止sql注入的方法

Talk is cheap,show me the code.
问题代码:

connect_error){
        die('connect error:'.$mysqli->connect_errno);
}
$mysqli->set_charset('UTF-8'); // 设置数据库字符集
$username = isset($_GET['username']) ? $_GET['username'] : '';
$password = isset($_GET['password']) ? $_GET['password'] : '';
$sql = "select * from t24 where username='$username' and password= '$password'";
echo "$sql
"; $result = $mysqli->query("$sql"); $data = $result->fetch_all(); // 从结果集中获取所有数据 if (empty($data)) { echo "登录失败"; } else { echo "登录成功"; } echo "
"; print_r($data); ?>

sql注入攻击:
http://localhost/index.php?username=tmd' or '1=1
sql语句变为:
select * from d_table where username = 'tmd' or '1=1' and password=''
登录成功!

解决方案:

1.参数的过滤

connect_error){
        die('connect error:'.$mysqli->connect_errno);
}
$mysqli->set_charset('UTF-8'); // 设置数据库字符集
$username = isset($_GET['username']) ? $_GET['username'] : '';
$password = isset($_GET['password']) ? $_GET['password'] : '';

//增加对输入用户名密码的判断,如果不是字母或者数字,就直接提示格式错误而退出。
if( !preg_match("/^[a-zA-Z0-9]{1,}$/",$username) || !preg_match("/^[a-zA-Z0-9]{1,}$/",$password) ) {
        die("You input username and password  format error ");
}

$sql = "select * from t24 where username='$username' and password= '$password'";
echo "$sql
"; $result = $mysqli->query("$sql"); $data = $result->fetch_all(); // 从结果集中获取所有数据 if (empty($data)) { echo "登录失败"; } else { echo "登录成功"; } echo "
"; print_r($data); ?>

对用户输入的用户名和密码,进行了正则的匹配,不符合规则的终止程序执行,参数校验不要忘记!

  1. addslashes()函数转义特殊字符
$sql = "select * from t24 where username='" . addslashes($username) . "' and password= '" . addslashes($password) . "'";

再次攻击:
http://localhost/index.php?username=tmd' or '1=1
sql语句变为:
select * from d_table where username = 'tmd\'or\'1=1' and password=''
登录失败!

你可能感兴趣的:(php层防止sql注入的方法)