Australian Made and Owned

Check if Headers Have Already Been Sent in PHP

Most PHP programmers would have come across this old chestnut before:
Cannot modify header information – headers already sent by page.php line 42

This can happen when you try doing a HTTP redirect or send HTTP 404, as it can happen whenever you try to send headers once they’ve already been sent. When a user sees this, they are basically left high and dry, often on a blank page. The solution is simple:

Detect if Headers Have Already Been Sent

Whenever you call header(); , call headers_sent(); first!

Example:

1
2
3
4
5
6
7
    if (!headers_sent()) {
        header('Location: ' . (!$absolute ? HOME_URL : "") . $page);
        die();
    } else {
        echo "\n\n<p>Couldn't redirect to " . htmlentities((!$absolute ? HOME_URL : "") . $page) . ", headers already sent.</p>\n\n";
        //do something here...
    }

Of course you should probably do thing useful



Did you like this post?
Email Send to a friend Add to Technorati Favorites

AddThis Social Bookmark Button
AddThis Feed Button

Leave a comment

1 Comment

  1. Tim Cinel » Blog Archive » 2009-07-22 - My Daily Summary

    [...] Check if Headers Have Already Been Sent in PHP – logon2 Blog – Better use of the web for everybody [...]

    2009/07/23 @ 10:08

RSS feed for comments on this post. TrackBack URL