PHP 和 Mysqli 中的登录错误脚本


Login Error script in PHP and Mysqli

好的,我知道这是错误的方法,我没有实现盐和其他小的安全提示但是现在我需要了解这里的问题是什么,然后我可以在脚本中实现其他安全功能,感谢您的帮助:)运行此脚本时,脚本返回登录错误,我可以理解为什么,我打印密码 $_POST['password'] 并且在数据库上相同,但是当尝试打印 $col 2(密码从数据库获取)时,什么也没返回。这是代码:

<?php
$mysqli = new mysqli("localhost", "root", "*******", "test");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s'n", mysqli_connect_error());
    exit();
}
/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT username, password FROM users WHERE username=? AND password=?")) {
    $stmt->bind_param("ss" , $username, $password);
    $stmt->execute();
    /* bind variables to prepared statement */
    $stmt->bind_result($col1, $col2);
    $stmt->store_result();
    /* fetch values */
    while ($stmt->fetch()) {
        printf("%s %s'n", $col1, $col2);
    }
    if($col1 && $col2 == $username && $password){
    $_SESSION['Admin']; //test - not to be implemented
    session_start(); //Test - not to be implemented
    header("location index2.php");
    }else{echo "Login Error";} 
    /* close statement */
    $stmt->close();
}
/* close connection */
$mysqli->close();
?>
if($col1 && $col2 == $username && $password){

此语句检查$col1是否TRUE$col2 == $username$password是否TRUE

这种情况永远不会为真,您的脚本将始终显示该错误消息。

请考虑以下示例:

$username = $col1 = 'user';
$password = $col2 = 'pass';
var_dump($col1 && $col2 == $username && $password);

这将返回bool(false)

因此,要解决此问题,您可以按如下方式更改代码:

if($col1 == $username && $col2 == $password) {
if($col1 && $col2 == $username && $password)

是什么? :)

在 php 中,这意味着如果 $col1$col2 具有零以外的任何值,$username$password 也有 0 以外的值,那么没关系

你需要创建类似的东西

if($col1 == $username && $col2 == $password)

如果将 MD5 哈希保留在数据库中,请使用

if($col1 == $username && $col2 == md5($password))

或者在具有MD5功能的MySQL中执行此操作。

我注意到您在printf("%s %s'n", $col1, $col2);后开始会话会导致headers already sent

$_SESSION['Admin'];这也会引起注意,因为此变量未定义

另一个问题是 header() 函数。您无法在此函数之前打印任何内容,因为它也会导致"标头已发送"。

一些明显的问题:

session_start(); 必须在任何 $_SESSION 变量使用之前

header("location index2.php");headers必须在任何其他东西之前发送

header("location index2.php");location 后没有冒号

除了其他人在答案中注意到的问题外,您还混合了过程式 mysqli 语句和面向对象的 mysqli 语句。

由于您从初始化new mysqli()开始,因此必须遵循面向对象的语法。

mysqli_connect_errno()更改为$mysqli->connect_errno