Ricky
Ricky

Reputation: 181

Does PHP continue to execute after a PHP redirect?

I'm making a website that does a lot of PHP redirects depending on different scenarios.. Like so...

header("Location: somesite.com/redirectedpage.php");

I'm just trying to get a firm understanding of how the redirect works, for securities sake. My question is, does PHP continue to execute after this header call?

For example... Would the echo still get executed in this bit of code?

function Redirect($URL)
{
    header("Location: " . $URL);
}

Redirect("http://somesite.com/redirectedpage.php");
echo("Code still executed");

If so... Would me changing the Redirect function to this... make it the echo not execute but still redirect?

function Redirect($URL)
{
    header("Location: " . $URL);
    exit(1);
}

Redirect("http://somesite.com/redirectedpage.php");
echo("Code still executed");

I'm just trying to get a firm understanding of how the redirect works, for securities sake.

Upvotes: 2

Views: 1037

Answers (2)

Aparna
Aparna

Reputation: 255

The header command doesn't interrupt the flow of your code. Even if that is encountered, your page is still downloaded by the browser, even if it isn't show. Consider 404 pages, which (despite being errors) are still processed by the browser (though they are rendered while redirects are not).

You can output a lot more headers than just Location headers with header, most of which you don't want to stop your code execution. If you want to stop code execution, you need to call exit explicitly.

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227280

All the header() statement does is modify the headers your webserver (Apache, nginx, etc.) send to your browser. You've added a Location: header to the page, which tells the browser to redirect to that page. Everything else in the PHP script will execute, including your echo, but you probably won't see it because you are going to be redirected to a new location.

Upvotes: 7

Related Questions