PHP Headers and 301 Forwarding – Output Buffering ob_start() for Errors

PHP headers are used to send a message to the browser. The message can be something like forward to a new URL, give a 404 error, tell visitors that the page has moved permanently or give a 301 moved permanently status, tell the content type of the page, tell when the page expires or prompt the user to start downloading a file.

PHP headers should be the first thing that is outputted to the browser. So, remember to place headers() before any other php code that outputs something to the browser. You can perform calculations, but you cannot output anything before headers. If outputs are already sent, headers do not work and they give a headers already sent error. If you want, you can use Output Buffering to delay the output sent to the the browser so that the “Warning: Cannot modify header information – headers already sent by (output)” error can be avoided.

A simple use of header

Note: After redirection, any subsequent code placed after header is not executed.

301 Moved Permanently using Header

You can also redirect while sending a message that the page has been moved permanently, i.e. “301 Moved Permanently status”. This is useful for SEO.


Redirecting After Few Seconds

Headers can be used to redirect a user to another page after a few seconds. The time in between is used to give out a message that the user is being redirected.


404 Error using Header

If you need to throw a “404 Not Found” error, headers can do so. For that:

Note: You can also give out other HTTP errors.

Facilitating a File Download using Header

You can use headers so that once it is activated, a file is downloaded. This is useful if you want to force download files like .jpg or .pdf files which normally open in a modern browser.


Cache Control using Headers

Headers can also be used to tell the browser to not cache the contents of a certain page. You can set the expiry date as well. The expiry date is set in the past to disable caching.



We can use getallheaders() to get all the HTTP headers. This one stores the headers in an array.

Continuing to the above example:

Headers and Output Buffering

Output buffering is used if there are code that are outputted before headers are sent. Without output buffering, you get an error.


With output buffering:

You may also like

Comments are closed here.


Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers