1

This is my code for checking access.

$query = "SELECT user_table.status, expire FROM user_table WHERE username = ?";

if($stmt = $mysqli->prepare($query)){
    $username = phpCAS::getAttribute('uid');
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $stmt->store_result();
    $returned_amount = $stmt->num_rows;


    if($returned_amount>1)
        die("To many user names exists for you!");
    else if(empty($returned_amount))
        header("Location: /101/index.php?type=nouser");


    $stmt->bind_result($status, $expire);
    $stmt->fetch();
    $stmt->free_result();
    $stmt->close();

    if($expire != '0000-00-00 00:00:00' && strtotime($expire) <= time())
        header('Location: /101/index.php?type=expired');

    $access = $status;

}else die("Failed to prepare!");

?>

However when $returned_amount == 0.

it doesn't hit header("Location: /101/index.php?type=nouser");

If I change the code to the following, it fixes the problem, but I don't see why changing it would help.

if($returned_amount>1)
    die("To many user names exists for you!");
else if(empty($returned_amount)){
    header("Location: /101/index.php?type=nouser");
    exit();
}

If I remove the exit();, the header won't be executed.

user2864740
  • 60,010
  • 15
  • 145
  • 220
Arian Faurtosh
  • 17,987
  • 21
  • 77
  • 115
  • `header()` is a general function to set an HTTP header. It's commonly used to set the redirect URI, but it doesn't have any magic behavior built in based on what type of header you're sending. You can also use it to set cookies, change the HTTP response code, add custom debugging information, etc. – Sam Dufel Mar 17 '14 at 18:58

2 Answers2

9

Just using header() does not mean the code stops executing. Whenever using header() to redirect you need to explicitly call exit() to stop execution of the script.

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • It just seems weird that sometimes the code stops executing and other times it continues. Without the fix, the could would be redirected to `header('Location: /101/index.php?type=expired');` instead, which doesn't have `exit()` – Arian Faurtosh Mar 17 '14 at 19:26
  • There are factors that influence when the page stops executing so the inconsistency you see is normal. That's why using `exit()` important. It guarantees a consistent result. – John Conde Mar 17 '14 at 19:28
1

Make sure there is no whitespace or any other characters that gets outputted in the page. Header() won't work otherwise. Adding exit() stops this from happening. Try removing the ?> at the end of your script as well (it will still work without the enclosing bracket). However it's best that you exit the script once header("Location: ... ") is run because it removes this problem and that's what you intend to do anyway (to quit this page and to go to another page)

Freeman
  • 1,201
  • 1
  • 11
  • 20