2

我决定搬到 mysqli,因为当人们发现我的 mysql 代码时,我一直很生气 :-)

有人可以验证以下内容是否正确,一切正常,但我只是想确保在进入网站的其余部分之前我没有做愚蠢的事情或存在安全风险。这是用于登录时检查用户名/密码的 php。

<?php
//Start session
session_start();

//Include database connection details
require_once('db_connect.php');

//Array to store validation errors
$errmsg_arr = array();

//Validation error flag
$errflag = false;


// cleanup POST variables
$username = mysqli_real_escape_string($mysqli, stripslashes(trim($_POST['username'])));
$password = mysqli_real_escape_string($mysqli, stripslashes(trim($_POST['password'])));

//Input Validations
if($username == '') {
    $errmsg_arr[] = 'Username required';
    $errflag = true;
}
if($password == '') {
    $errmsg_arr[] = 'Password required';
    $errflag = true;
}

//If there are input validations, redirect back to the login form
if($errflag) {
    $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
    session_write_close();
    header("location: logon.php");
    exit();
}

//Load and run query
$result = mysqli_query($mysqli, "SELECT * FROM auth WHERE username='$username' AND password='$password'");

if ($result->num_rows) {
//Login Successful
        session_regenerate_id();
        //Set session variables
        $member = $result->fetch_assoc();
        $_SESSION['SESS_MEMBER_ID'] = $member['ID'];
        $_SESSION['SESS_USERNAME'] = $member['username'];
        $_SESSION['SESS_FIRST_NAME'] = $member['fname'];
        $_SESSION['SESS_PASSWORD'] = $member['password'];
        $_SESSION['SESS_AUTH_LEVEL'] = $member['auth_level'];
        session_write_close();
        header("location: index");
        exit();
    }else {
        //Login failed
        $errmsg_arr[] = 'user name or password not found';
        $errflag = true;
        if($errflag) {
            $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
            session_write_close();
            header("location: logon.php");
            exit();
        }
    }
mysqli_close($mysqli); 
?>

非常感谢!

4

1 回答 1

0

好吧,你会想在这里使用准备好的语句,因为你没有执行静态SQL 查询——这mysqli_query()就是要使用的。

所以,这就是你需要做的:

  1. 不要打扰该// cleanup POST variables部分。

  2. 更改//Load and run query部分以使用准备好的语句。

  3. 首先,我们要准备它: http: //php.net/manual/en/mysqli.prepare.php

    $query = mysqli_prepare($mysqli, "SELECT * FROM auth WHERE username=? AND password=?");

  4. 那么我们要给Mysqli什么呢?标记是:http ://www.php.net/manual/en/mysqli-stmt.bind-param.php

    $query->bind_param('ss', $username, $password);

然后,使用bind_resultand fetch(参见http://www.php.net/manual/en/class.mysqli-stmt.php上的索引)获取结果并存储到会话变量中。

于 2013-06-04T15:16:41.640 回答