14

I use the same php script for including and for ajax loading. It is some random catalog items which are loaded with the page and can be loaded with ajax. I need to use header() function there only if it is loaded via ajax.

When I use header function and the output already started I get php warning about it. How does php know that output already started? What is the best way to determine that, and not to call header function?

Thanks.

foreline
  • 3,751
  • 8
  • 38
  • 45

6 Answers6

25

http://php.net/manual/en/function.headers-sent.php

// If no headers are sent, send one
if (!headers_sent()) {
    header('...');
    exit;
}
Jake
  • 775
  • 9
  • 17
  • Thanks a lot! Just what I needed. And by the way why exit? – foreline Jan 20 '11 at 21:31
  • 1
    The use of exit is straight from the referenced PHP manual for a 'header: Location' call which requires it. In your case you should not add it, or you will break the output. – tomwalsham Jan 20 '11 at 21:33
  • Yeah sorry, I copied it straight from the manual and forgot to remove it :) – Jake Jan 20 '11 at 21:41
6

There's an easy built-in for that:

if (!headers_sent()) {
    header('Your header here');
}

Not much more to add :)

tomwalsham
  • 781
  • 4
  • 4
3

One option is to call ob_start() at the beginning, which buffers all your output. That way you can send headers any time.

Tesserex
  • 17,166
  • 5
  • 66
  • 106
2

headers_sent() returns true if you cannot send additional headers.

Floern
  • 33,559
  • 24
  • 104
  • 119
0

Just remove the empty line before the code starts and add exit; after your output ends.

Elangathir
  • 41
  • 2
  • There's no code in the question - how do you know what's in there and what isn't? Most of the current answers suggest using `headers_sent()` - is there a reason why your suggestion might be better? – andrewsi Jul 22 '14 at 04:28
0

If you sent anything to client, the output started.

For example even a single html tag, it's already output.

You can either structure your application so that this doesn't happen, or you can turn on output buffering:

http://php.net/manual/en/function.ob-start.php

CodeVirtuoso
  • 6,318
  • 12
  • 46
  • 62