Logo Background RSS

How to detect if headers are already sent in PHP

  • Written by vinuvinu 1 Comment1 Comment Comments
    Last Updated: October 6th, 2006
    I’m sure most of us have encountered the following error message while playing with the header function in PHP

    “Cannot modify header information - headers already sent by …”

    How can we detect whether the script has already sent out headers? PHP has a function headers_sent() which allows you to check if the headers are already sent out before you take any action. Here’s how you could use the function in your code:

    if(headers_sent())
    { //if headers already sent out print some message.
    echo "Please go to yahoo.com“;
    }
    else{
    //send the user automatically to test.php
    header(’Location: http://yahoo.com’);
    }

    The code above checks to see if PHP has already sent out headers anywhere else. If so, the script will print a message on screen, else the user is automatically redirected to the yahoo.com.

    Bookmark and share:
    • del.icio.us
    • Digg
    • StumbleUpon
    • BlinkList
    • blogmarks
    • Furl
    • Slashdot
    • Spurl
    • Technorati
    • YahooMyWeb
    • description
    • Facebook
    • Google
    • Live
    • Ma.gnolia
    • NewsVine
    • Reddit
    • TwitThis

Advertisement

  1. #1 hammertscrew
    January 22nd, 2008 at 8:34 pm

    better:

    function safeRedirect($url) {
    if(headers_sent()) {
    echo “Please go to “.$url.”“;
    echo “\n”;
    echo “window.location.href=’”.$url.”‘;\n”;
    echo “\n”;
    echo “\n”;
    echo “\n”;
    }
    else{
    header(’Location: ‘.$url);
    }

    exit;
    }

    Don’t forget the closing ‘exit’, otherwise the script will continue executing.

    Post ReplyPost Reply
Leave a Comment