如何制作安全的登录脚本

时间:2015-02-04 05:25:35

标签: php mysql mysql-real-escape-string

我正在尝试使登录脚本安全,以阻止我的网站黑客攻击。我试图在我的脚本中使用mysql_real_escape_string,如果我错了,任何人都可以指导我。

这是我的代码

    <?php
session_start();
include("lib/conn.php");

?>
<?php
$email=$_POST['user'];
$password=$_POST['password'];

if ($email && $password){

$query = "SELECT * FROM register WHERE email = '$email' AND password= '$password' and status = '1'";

mysql_real_escape_string($email);
mysql_real_escape_string($password);

$result = mysql_query( $query ) or die ("didn't query");
$num = mysql_num_rows( $result );
if ($num == 1){

$_SESSION['ocer']=$email;




header("Location: admin.php"); 


    } 
    else {







header("Location: index.php?l=1");


}
}

?>

2 个答案:

答案 0 :(得分:2)

1.-不要使用 mysql * 函数,因为已弃用,使用 mysqli _ * 函数或 PDO

2.-您应该使用预备语句,这是使用 mysqli _ * 函数的示例:

<?php
$email=$_POST['user'];
$password=$_POST['password'];

if ($email && $password){

$query = "SELECT email, password 
          FROM register 
          WHERE email = ? 
                AND password= ? 
                AND status = '1'";

$stmt = mysqli_prepare($link, $sql);

mysqli_stmt_bind_param($stmt, 'ss', $email, $password);

mysqli_stmt_execute($stmt);

mysqli_stmt_bind_result($stmt, $column1, $column2);

while (mysqli_stmt_fetch($stmt)) {
    echo "Column1: {$column1}, Column2: {$column2}";
}

?>

答案 1 :(得分:0)

首先。将PDO与bind参数一起使用。那你就不用担心注射了。

mysql_real_escape_string返回转义字符串,应在构造查询之前使用。使用就是这样:

$password = mysql_real_escape_string($password);

另外。不要通过密码和电子邮件检索。通过电子邮件检索密码并验证是否存在密码。

希望有所帮助

以下是示例:

session_start();
include("lib/conn.php");

//using isset to avoid warnings.
$email = isset($_POST['user']) ? $_POST['user'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;

//check if values are not null
if ($email !== null && $password !== null){

    //escape email
    $email = mysql_real_escape_string($email);

    //retrieve password by email and limit 1 result
    $query = "SELECT password FROM register WHERE email = '{$email}' and                         status = '1' LIMIT 1";

    //run query
    $result = mysql_query( $query ) or die ("didn't query");

    //validate if query run correctly
    if (!$result) {
        echo 'Could not run query: ' . mysql_error();
        exit;
    }

    //fetch row
    $row = mysql_fetch_row($result);

    //validate result
    if ($row['password'] == $password){
        $_SESSION['ocer']=$email;
        header("Location: admin.php"); 
    } else {
        header("Location: index.php?l=1");
    }
}