致命错误:未捕获错误:调用未定义函数mysql_real_escape_string()

时间:2016-10-24 14:24:53

标签: php mysql-real-escape-string

我试图从登录表单中转义输入,以防止sql注入。但我得到的错误是:

  

致命错误:未捕获错误:在F:\ Apache24 \ htdocs \ Site1 \ user \ login.php中调用未定义函数mysql_real_escape_string():17堆栈跟踪:F:\ Apache24 \ htdocs中抛出#0 {main}第17行的Site1 \ user \ login.php

我还没有清理或验证用户输入,因为我还在构建页面,但我想测试它是否正确连接到数据库。这是登录页面的代码:

<!DOCTYPE html>
<?php 
    include('../includes/pdo_connect.php');
    $expiry = time()+60*60*24;
    if(!setcookie('userdata[user_id]', $user_id, $expiry, '', '', '', TRUE)){
        echo "<script>alert('could not set cookie');</script>";
    }
?>
<html>
<head>
    <title>Login</title>
    <link rel="stylesheet" type="text/css" href="../styles/login_style.css">
    <?php 
        global $con;

        if(isset($_POST['login_ok'])){
            $email = mysql_real_escape_string($_POST['email']);
            $pass = mysql_real_escape_string($_POST['password']);

            try{
                $query = "select * from user where user_email=':email' and password=':pass'";
                $stmt = $con->prepare();

                $stmt->bindParam(':email', $email, PDO::PARAM_STR);
                $stmt->bindParam(':pass', $pass, PDO::PARAM_STR);

                $stmt->execute();

                $result = $stmt->fetchAll();

                foreach($result as $row) {
                    $user_id = $row['user_id'];
                    //$user_first_name = $row['user_first_name'];
                    header("Location:profile.php");
                }

            } catch(PDOException $e){
                echo "Error: ".$e->getMessage();
            }
        }
    ?>
</head>
<body>
    <div class="wrapper">
        <header>

        </header>
        <div class="form_div">
            <div class="form">
                <form id="register_form" method="post" action="" autocomplete="autocomplete">
                    <table>
                        <tr>
                            <td id="label">Email: </td>
                            <td id="input"><input type="text" name="email" required="required" id="input_box"></td>
                        </tr>
                            <td id="label">Password: </td>
                            <td id="input"><input type="password" name="password" id="input_box"></td>
                        </tr>
                        <tr id="button_row">
                            <td colspan="2"><input type="reset" value="Reset" id="button">
                            <input type="submit" value="Login" id="button" name="login_ok"></td>
                        </tr>
                    </table>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

mysql_ API已过时,已从PHP中删除(支持PDO和mysqli_)。

你正在使用PDO,所以你应该使用PDO方法来防御SQL注入,你已经是:

$stmt->bindParam(':email', $email, PDO::PARAM_STR);足以抵御SQL注入。