header(location:URL) does not work

I am retrieving data from a database to verify user credentials. In case of a password mismatch, I wish to redirect the user to the login page. However, this never happens. Instead, I am redirected to chat_main.php.

It works fine for all other cases (invalid email, valid email and password combination).

Here is my code:

<?php
session_start();
require_once("config/db_connect.php");
$usr=$_POST['email'];
$pwd=$_POST['password'];
$q="SELECT * FROM userdata WHERE email=\"$usr\"";
$info=mysql_query($q, $conn);
if(mysql_num_rows($info)!=1){
    header("Location: login.php?err=1");
}
else{
    while($data=mysql_fetch_array($info)){
        if($pwd!=$data['pwd']){
            header("Location: login.php?err=1");
        }
        $usr=$_SESSION['username']=$data['fname'];
        header("Location: chat_main.php?username=$usr");
    }
}
?>

Why is it behaving thus, and how can this be resolved?

Upvotes: 0

Views: 193

Answers (2)

asdawrqtgf
asdawrqtgf

Reputation: 640

<?php
session_start();
require_once("config/db_connect.php");
$usr=$_POST['email'];
$pwd=$_POST['password'];
$q="SELECT * FROM userdata WHERE email=\"$usr\"";
$info=mysql_query($q, $conn);
if(mysql_num_rows($info)!=1){
header("Location: login.php?err=1");
exit;
}
else{
while($data=mysql_fetch_array($info)){
    if($pwd!=$data['pwd']){
        header("Location: login.php?err=1");
        exit;
    }
    $usr=$_SESSION['username']=$data['fname'];
    header("Location: chat_main.php?username=$usr");
    exit;
}
}
?>

Should work, because you have to terminate the script after sending header.

Upvotes: 0

aynber
aynber

Reputation: 23001

Add exit; after each header line, to make the script exit and actually process the header redirect. Otherwise, it will keep running and will hit the next header redirect..

Upvotes: 2

Related Questions