Skip to content
Fragmented Development

Safeguard Your Redirects

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?

Not always.

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):

  1. Enable output buffering: I haven't tried this one myself, so make sure to verify it works.
  2. 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.

Tags: php


Add Your Comment