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.

6 Answers 6

25

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

// If no headers are sent, send one
if (!headers_sent()) {
    header('...');
    exit;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot! Just what I needed. And by the way why exit?
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.
Yeah sorry, I copied it straight from the manual and forgot to remove it :)
6

There's an easy built-in for that:

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

Not much more to add :)

Comments

3

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

Comments

2

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

Comments

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

Comments

0

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

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.