浅谈PHP之对于用户提交数据的过滤

自己刚学了PHP,尝试去看一些网上的代码,还好可以大概看懂,

身为一个网络安全爱好者,当然关心PHP开发所引发的安全问题,

作为新手应该首先注意的是用户的提交内容,他们很有可能是大灰阔哦!

看如下一个简单的登入表单

<html> 
 
<head> 
 
<title>Login</title> 
 
</head> 
 
<body> 
 
<form action=”verify.php” method=”post”> 
 
<p><label for='user'>Username</label> 
 
<input type='text' name='user' id='user'/> 
 
</p> 
 
<p><label for='pw'>Password</label> 
 
<input type='password' name='pw' id='pw'/> 
 
</p> 
 
<p><input type='submit' value='login'/></p> 
 
</form> 
 
</body> 
 
</html> 

下面是一个新手对表单的处理

<?php 
 
$okay = 0; 
 
$username = $_POST['user']; 
 
$pw = $_POST['pw']; 
 
$sql = “select count(*) as ctr from users where username='”.$username.”' and password='”. $pw.”' limit 1″; 
 
$result = mysql_query($sql); 
 
while ($data = mysql_fetch_object($result)){ 
 
if ($data->ctr == 1){ 
 

 
$okay = 1; 
 
} 
 
} 
 
if ($okay){ 
 
$_SESSION['loginokay'] = true; 
 
header(”index.php”); 
 
}else{ 
 
header(”login.php”); 
 
} 
 
?> 



这里没有对用户信息进行转义,任何的SQL注入都将成功。

应该利用mysql_real_escape_string()进行转义就可以了,但我不同意网上说用了就,可以过滤一切SQL注入,因为此函数不过滤%和_ 这里要请教大牛们了

接下来要讲一讲正则表达式用来限制GET变量

?php 
 
$pid = $_GET['pid']; 
 
if (strlen($pid)){ 
 
if (!ereg(”^[0-9]+$”,$pid) && strlen($pid) > 5){ 
 
//do something appropriate, like maybe logging them out or sending them back to home page 
 
} 
 
} else { 
 
//empty $pid, so send them back to the home page 
 
} 
 
//we create an object of a fictional class Page, which is now 
 
//even more protected from evil user input 
 
$obj = new Page; 
 
$content = $obj->fetchPage($pid); 
 
//and now we have a bunch of PHP that displays the page 
 
?> 

这下就不会,在数据库被塞入超大数值了,而且不会报错,一般小灰阔是想不到的。



欢迎网络安全爱好者与我交流。




posted @ 2012-01-29 00:12  稻草哥  阅读(3305)  评论(0编辑  收藏  举报