foreline
foreline

Reputation: 3821

PHP: how to know if output already started?

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.

Upvotes: 14

Views: 5591

Answers (6)

Elangathir
Elangathir

Reputation: 41

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

Upvotes: 0

CodeVirtuoso
CodeVirtuoso

Reputation: 6438

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

Upvotes: 0

Floern
Floern

Reputation: 33904

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

Upvotes: 2

tomwalsham
tomwalsham

Reputation: 781

There's an easy built-in for that:

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

Not much more to add :)

Upvotes: 6

Tesserex
Tesserex

Reputation: 17314

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

Upvotes: 3

Jake
Jake

Reputation: 785

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

// If no headers are sent, send one
if (!headers_sent()) {
    header('...');
    exit;
}

Upvotes: 25

Related Questions