Safeguard Your Redirects
Posted on 2008-05-15 (Updated on 2019-01-23)
Every once and a while, I allow a page to terminate itself by redirecting the user to another page with the header() function. This effectively stops script execution, because the user is sent to another page, right?
If output has been sent to the user ahead of the the header() call, nothing happens. PHP cannot modify headers after output has been sent to the user, so your redirect falls flat. You have two ways to remedy this situation (you can use both if you'd like):
- Enable output buffering: I haven't tried this one myself, so make sure to verify it works.
- Explicitly force the script to stop processing using the exit() function
I'm fond of calling exit(), because it stops a script dead in it's tracks without any fuss. If you explicitly tell PHP to quit processing, then there's nothing further to worry about.