Search code examples
phpif-statementforum

My PHP script is excecuting both if and else statements


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>';
  }
}
?>

Solution

  • 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.