Wex
Wex

Reputation: 15705

Does it matter whether or not you call exit after a header("Location: ") call?

I couldn't seem to find an answer until I found this post on exit over at php.net.

After sending the `Location:' header PHP will continue parsing, and all code below the header() call will still be executed.

Is this valid?

And to further this question, if it is valid, to what benefit does it have to leave exit out (and let the rest of the code run)?

Upvotes: 3

Views: 173

Answers (2)

genesis
genesis

Reputation: 50976

Yes it is valid, because headers are sent with another content. Script executes and AFTER that content&headers are sent to user.

Upvotes: 0

Paul
Paul

Reputation: 141837

Yes, that is valid. The header() function just sends a header to the browser along with the rest of your page which tells the browser to redirect. If you don't want the script to continue running then you should do an exit or die.

There may be cases where you want the script to continue running though as well, depending on the script. You may be keeping track of page hits or something and you might have code insert that into a database included at the bottom of every page. If you want it to track the hit before the redirect then you wouldn't want to exit early.

Another case you might want to continue running the code is if you have a timed redirect header, and want to display something to the user like Redirect to: http://xxxxxx in 5 seconds. So they have a chance to see where their browser's going before the redirect. You would probably only want to do that if you were redirecting them to an entirely different website though.

In most cases you do want to exit because you do not likely want to output anything to the browser in that case and the extra code will just slow down your redirect.

Upvotes: 5

Related Questions