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条)

报告相同问题?