1

可能重复:
在 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');
                }
            }
        }
    }
?>
4

1 回答 1

4

你应该停止使用mysql_*函数。它们正在被弃用。而是使用PDO(从 PHP 5.1 开始支持)或mysqli(从 PHP 4.1 开始支持)。如果您不确定要使用哪一个,请阅读这篇文章

另外,请阅读此交流:如何防止 PHP 中的 SQL 注入?

于 2012-08-16T13:31:54.753 回答