什么sql注入?sql是怎样注入?又怎样防止SQL被注这些问题相信老手们都很清楚了,这里主要是对于一些初学者举的一个例子闲话少说我们之间进入正题
1、我们先建一个数据表如图说是,相信大家都会,代码就不写了
2、连接数据库执行一个没做处理的正常的查询语句:
$con = mysql_connect("localhost","root","");
mysql_select_db("tb", $con);
$result = mysql_query("select * from abc where name='abc' and pass='www'");
$row = mysql_fetch_array($result);
echo "name:".$row['name']."
";
echo "pass:".$row['pass'];
//输出结果
//name:abc
//pass:www
?>
3、sql注入查询,我们将 name值设为'123 or 1=1',pass值设为'123 or 1=1'
实际上就形成了另一条语句把之前的“且”改成了“或”:
$result = mysql_query("select * from abc where name='123 or 1=1' and pass='123 or 1=1'); 一样可以查询出结果,这样就成功的通过sql注入了
$name='123 or 1=1';
$pass='123 or 1=1';
$con = mysql_connect("localhost","root","");
mysql_select_db("tb", $con);
$result = mysql_query("select * from abc where name=$name and pass=$pass");
$row = mysql_fetch_array($result);
echo "name:".$row['name']."
";
echo "pass:".$row['pass'];
//输出结果
//name:100
//pass:123
?>
4、怎样防止注入呢,我们可以通过对查询时的条件变量进行过滤,把空格和特殊字符过滤掉,如代码所示:
$name='123 or 1=1';
$pass='123 or 1=1';
$name=str_replace(' ','',$name); //清除空格 结果为'123or1=1'
$pass=str_replace(' ','',$pass); //清除空格 结果为'123or1=1'
$name=addslashes($name); //过滤掉特殊字符如反斜杠
$pass=addslashes($pass); //过滤掉特殊字符如反斜杠
$con = mysql_connect("localhost","root","");
mysql_select_db("tb", $con);
$result = mysql_query("select * from abc where name='$name' and pass='$pass'");
$row = mysql_fetch_array($result);
echo "name:".$row['name']."
";
echo "pass:".$row['pass'];
//输出结果
//name:
//pass:
?>
这样语句就变成如下说是,就没法执行查询数据了
$result = mysql_query("select * from abc where name=123or1=1' and pass=123or1=1');
网上有很多详细讲解,我这里只是简单演示一个php sql漏洞语句,怎样通过php sql注入漏洞,和怎样防止漏洞注入的例