可能的重复项:
防止 PHP 中的 SQL 注入的最佳方法
我是PHP的新手。我听说过很多(并读过)SQL注入攻击。我已经习惯了以下编写PHP代码的方式。有人可以告诉我这是否容易受到SQL攻击。另外,我可以通过什么方式改进此代码以抵御 SQL 攻击?
<?php
if($_POST['submit']){
$email = protect($_POST['email']);
$password = protect($_POST['password']);
$md5password=MD5($password);
if(!$email || !$password){
echo '<span style="color: red;" /><center>You need to fill in your <b>User Name</b> and <b>Password</b>!</center></span>';
}else{
$res = mysql_query("SELECT * FROM `employer` WHERE `email` = '".$email."'");
$num = mysql_num_rows($res);
if($num == 0){
echo '<span style="color: red;" /><center>The <b>E Mail ID</b> you supplied does not exist!</center></span>';
}else{
$res = mysql_query("SELECT * FROM `employer` WHERE `email` = '".$email."' AND `password` = '".$md5password."'");
$num = mysql_num_rows($res);
if($num == 0){
echo '<span style="color: red;" /><center>The <b>Password</b> you supplied does not match the one for that E Mail ID!</center></span>';}else{
$row = mysql_fetch_assoc($res);
$_SESSION['uid'] = $row['id'];
echo "<center>You have successfully logged in!</center>";
$time = date('U')+50;
mysql_query("UPDATE `employer` SET `online` = '".$time."' WHERE `id` = '".$_SESSION['uid']."'");
mysql_query("UPDATE employer (date) VALUES (NOW())");
header('Location: loggedin_employer.php');
}
}
}
}
?>
您应该
停止使用mysql_*
函数。它们正在被弃用。而是使用 PDO(从 PHP 5.1 开始支持)或 mysqli(从 PHP 4.1 开始支持)。如果您不确定要使用哪一个,请阅读本文。
另外,请阅读此交流:如何防止 PHP 中的 SQL 注入?