doujiao1905 2013-10-07 21:40 采纳率: 100%
浏览 48
已采纳

我的PHP脚本正在执行if和else语句

I realise this question has been answered before however each are all specific to everyone's code. I would appreciate it if someone could tell me why both if and else statements are executing. The script is part of a login script for a piece of forum software I am developing. Thanks Robbie

<?php
$username = $_POST['username'];
$password = md5($_POST['password']);
session_start();
include($_SERVER['DOCUMENT_ROOT']."/forum/config.php");

$connect = mysqli_connect($DBHOST,$DBUSER,$DBPASS,$DBNAME);
if ($connect->connect_errno) {
    die('Connection Error: ' . $connect->connect_errno);
}
$query = $connect->query("SELECT * FROM forum_users");
while($row = $query->fetch_array()){
  if (($row['username'] == $username) AND ($row['password'] == $password)) {
        $_SESSION['username']=$username;
        echo '<script language="javascript">';
        echo 'window.location.href = "../forum/"';
        echo '</script>';
  } else {
        echo '<script language="javascript">';
        echo 'window.location.href = "../forum/login?password=wrong"';
        echo '</script>';
  }
}
?>
  • 写回答

2条回答 默认 最新

  • dongyaoxiu6244 2013-10-07 21:44
    关注

    You are fetching all user data from the database (SELECT * FROM forum_users). If you have more than one user with different name or password the else statement is executed independend of the username and password input because the username and password can only match one entry in the database.

    You should remove the while loop and replace it by

    $row = $query->fetch_array();
    if ($row) {
        if (($row['username'] == $username) AND ($row['password'] == $password)) {
            $_SESSION['username']=$username;
            echo '<script language="javascript">';
            echo 'window.location.href = "../forum/"';
            echo '</script>';
        } else {
            echo '<script language="javascript">';
            echo 'window.location.href = "../forum/login?password=wrong"';
            echo '</script>';
        }
    }
    

    EDIT

    You can also do the whole password check in the query with

    $secureUsername = mysql_real_escape_string($username);
    $securePassword = mysql_real_escape_string($password);
    $query = $connect->query("SELECT * FROM forum_users WHERE username='" . $secureUsername . "' AND password='" . $securePassword . "'");
    

    and than check if the number of rows equals one.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大