Talk is cheap,show me the code.
问题代码:
<?php
$servername="127.0.0.1";
$dbuser="muke_user";
$dbpassword="9Gcag71Gaa";
$dbname="muke";
$mysqli = new mysqli($servername,$dbuser,$dbpassword,$dbname); //配置MySQL连接
if($mysqli->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<br/>";
$result = $mysqli->query("$sql");
$data = $result->fetch_all(); // 从结果集中获取所有数据
if (empty($data))
{
echo "登录失败";
} else {
echo "登录成功";
}
echo "<br/>";
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.参数的过滤
<?php
$servername="127.0.0.1";
$dbuser="muke_user";
$dbpassword="9Gcag71Gaa";
$dbname="muke";
$mysqli = new mysqli($servername,$dbuser,$dbpassword,$dbname); //配置MySQL连接
if($mysqli->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<br/>";
$result = $mysqli->query("$sql");
$data = $result->fetch_all(); // 从结果集中获取所有数据
if (empty($data))
{
echo "登录失败";
} else {
echo "登录成功";
}
echo "<br/>";
print_r($data);
?>
对用户输入的用户名和密码,进行了正则的匹配,不符合规则的终止程序执行,参数校验不要忘记!
- 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=''
登录失败!