Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Header redirects falling through if statements

I have some code to log how many password attempts have been tried that looks like this:

<?php
/* Access denied */
$_SESSION['error'] = "invalidlogin";

if (isset($_SESSION['tries']))
{
    if ($_SESSION['tries'] == 5)
    {
        //TODO: Redirect somewhere nicer and more descriptive
        header("location:/index.php");
    }
    else
    {
        $_SESSION['tries']++;   
    }
}
else
{
    $_SESSION['tries'] = 0; 
}

header("location:/login.php");
?>

I know it is counting up to five and then stopping cuz I tested it by echoing $_SESSION['error'] on login.php

PHP never redirects when it hits

header("location:/index.php");

But it always keeps going and then redirects to

header("location:/login.php");

How can I get PHP to redirect as soon as it hits the index.php redirect?

Do I just set a boolean after the index.php redirect and check it on the login.php redirect?

EDIT: To clarify, I have already defined a session_start(); don't worry about that.

like image 378
Joe Bentley Avatar asked Mar 12 '26 06:03

Joe Bentley


2 Answers

header("location:/index.php");
exit();
like image 131
HBublitz Avatar answered Mar 15 '26 04:03

HBublitz


A redirect only takes effect AFTER it's been sent to the client's browser and the browser initiates a new request (which terminates the current request). Simply calling header() doesn't initiate the redirect - your script will keep running until it exits normally, the connection is closed and the webserver shuts down the script, or you explicitly terminate execution.

if you want a redirect header to take effect immediately, you need to terminate the script, which causes a flush of any pending output (including the redirect header):

header("Location: ...");
exit();
like image 44
Marc B Avatar answered Mar 15 '26 04:03

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!