Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Headers already been sent in PHP

Tags:

php

header

I think most of us know about the infamous "Headers already sent" error in PHP. Can I check someway if headers already have been sent?

It would be really handy to do such, before going all out with trying to set some SESSION data or similar.

Thanks!

like image 865
Industrial Avatar asked May 12 '10 16:05

Industrial


People also ask

How do I view headers in PHP?

The get_headers() function in PHP is used to fetch all the headers sent by the server in the response of an HTTP request.

What is HTTP header in PHP?

The header() function is an predefined PHP native function. With header() HTTP functions we can control data sent to the client or browser by the Web server before some other output has been sent. The header function sets the headers for an HTTP Response given by the server.


2 Answers

Yup, you can use the headers_sent function.

Checks if or where headers have been sent.

You can't add any more header lines using the header() function once the header block has already been sent. Using this function you can at least prevent getting HTTP header related error messages. Another option is to use Output Buffering.

headers_list may also be of interest, which returns an array of all headers sent.

like image 36
ryeguy Avatar answered Oct 13 '22 09:10

ryeguy


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'); exit; } 
like image 53
Russell Dias Avatar answered Oct 13 '22 09:10

Russell Dias