Cannot modify header information

     
This question's answers are a community effort. Edit existing answers to lớn improve this post. It is not currently accepting new answers or interactions.
When running my script, I am getting several errors lượt thích this:

Warning: Cannot modify header information - headers already sent by (output started at /some/tệp tin.php:12) in /some/tệp tin.php on line 23

The lines mentioned in the error messages contain header() và setcookie() calls.

Bạn đang xem: Cannot modify header information

What could be the reason for this? And how to lớn fix it?


No output before sending headers!

Functions that send/modify HTTP headers must be invoked before any output is made.summary ⇊Otherwise the gọi fails:

Warning: Cannot modify header information - headers already sent (output started at script:line)

Some functions modifying the HTTP. header are:

Output can be:

Unintentional:

Whitespace before or after ?>Previous error messages or notices

Intentional:

print, emang lại và other functions producing outputRaw sections prior code.

Why does it happen?

To understand why headers must be sent before output it"s necessaryto lớn look at a typical HTTPresponse. PHPhường scripts mainly generate HTML content, but also pass aphối of HTTP/CGI headers to lớn the webserver:

HTTP/1.1 200 OKPowered-By: PHP/5.3.7Vary: Accept-EncodingContent-Type: text/html; charset=utf-8PHP page output pageContent Some more output follows...

The page/output always follows the headers. PHPhường has to lớn pass theheaders to the webVPS first. It can only bởi that once.After the double linebreak it can nevermore amend them.

When PHP.. receives the first output (print, emang đến, ) it willflush all collected headers. Afterward it can sover all the outputit wants. But sending further HTTPhường headers is impossible then.

How can you find out where the premature output occurred?

The header() warning contains all relevant information tolocate the problem cause:

Warning: Cannot modify header information - headers already sent by(output started at /www/usr2345/htdocs/auth.php:52) in/www/usr2345/htdocs/index.php on line 100

Here "line 100" refers khổng lồ the script where the header() invocation failed.

The "output started at" note within the parenthesis is more significant.It denominates the source of previous output. In this example, it"s auth.phpvà line 52. That"s where you had to lớn look for premature output.

Typical causes:

Print, echo

Intentional output from print và emang lại statements will terminate the opportunity khổng lồ sover HTTP.. headers. The application flow must be restructured khổng lồ avoid that. Use functions& templating schemes. Ensure header() calls occur before messagesare written out.

Functions that produce output include

print, emang đến, printf, vprintftrigger_error, ob_flush, ob_end_flush, var_dump, print_rreadfile, passthru, flush, imagepng, imagejpeg

aý muốn others & user-defined functions.

Raw HTML areas

Unparsed HTML sections in a .php file are direct output as well.Script conditions that will trigger a header() điện thoại tư vấn must be notedbefore any raw blocks.

Use a templating scheme lớn separate processing from output lô ghích.

Place form processing code atop scripts.Use temporary string variables khổng lồ defer messages.The actual output lô ghích và intermixed HTML output should follow last.

Xem thêm: #1 Hit & Run Là Gì ? Cách Vừa Đánh Vừa Di Chuyển Trong Lmht Học Cách Vừa Tấn Công Vừa Di Chuyển

Whitespace before for "script.php line 1" warnings

If the warning refers to output inline 1, then it"s mostlyleading whitespace, text or HTML before the opening token.

Similarly it can occur for appended scripts or script sections:

?>PHP actually eats up a single linebreak after cthua kém tags. But it won"tcompensate multiple newlines or tabs or spaces shifted inlớn such gaps.

Error source mentioned as "Unknown on line 0"

It"s typically a PHPhường. extension or php.ini setting if no error sourceis concretized.

But it could also be any doubly loaded extension= modulegenerating an implicit PHP.. startup/warning message.

No error message

If you have sầu error_reporting or display_errors disabled per php.ini,then no warning will show up. But ignoring errors won"t make the problem goaway. Headers still can"t be sent after premature output.

So when header("Location: ...") redirects silently fail it"s veryadvisable khổng lồ probe for warnings. Reenable them with two simple commandsatop the invocation script:

error_reporting(E_ALL);ini_set("display_errors", 1);Or set_error_handler("var_dump"); if all else fails.

Speaking of redirect headers, you should often use an idiom likethis for final code paths:

exit(header("Location: /finished.html"));Preferably even a utility function, which prints a user messagein case of header() failures.

Output đầu ra buffering as a workaround

PHPs output bufferingis a workaround lớn alleviate this issue. It often works reliably, but shouldn"tsubstitute for proper application structuring & separating output from controlxúc tích và ngắn gọn. Its actual purpose is minimizing chunked transfers khổng lồ the webhệ thống.

It can likewise be engaged with a gọi khổng lồ ob_start();atop the invocation script. Which however is less reliable for multiple reasons:

It can conceal whitespace for HTML output. But as soon as the application lô ghích attempts to lớn sover binary nội dung (a generated image for example),the buffered extraneous output becomes a problem. (Necessitating ob_clean()as a further workaround.)

Both approaches therefore may become unreliable - in particular when switching betweendevelopment setups and/or production servers. This is why output buffering iswidely considered just a crutch / strictly a workaround.

See also the basic usage examplein the manual, & for more pros and cons:

But it worked on the other server!?

If you didn"t get the headers warning before, then the output bufferingphp.ini settinghas changed. It"s likely unconfigured on the current/new server.

Checking with headers_sent()

You can always use headers_sent() to lớn probe ifit"s still possible lớn... send headers. Which is useful lớn conditionally printinfo or apply other fallbaông xã logic.

if (headers_sent()) die("Redirect failed. Please clichồng on this link: ");else exit(header("Location: /user.php"));Useful fallbachồng workarounds are:

HTML tag

If your application is structurally hard lớn fix, then an easy (butsomewhat unprofessional) way to lớn allow redirects is injecting a HTML tag. A redirect can be achieved with:

Or with a short delay:

This leads to non-valid HTML when utilized past the section.Most browsers still accept it.

Both approaches however make acceptable fallbacks when genuine HTTP.. header()calls fail. Ideally you"d always combine this with a user-friendly message andclickable links as last resort. (Which for instance is what the http_redirect()PECL extension does.)

Why setcookie() & session_start() are also affected

Both setcookie() and session_start() need to skết thúc a Set-Cookie: HTTP. header.The same conditions therefore apply, and similar error messages will be generatedfor premature output situations.

(Of course, they"re furthermore affected by disabled cookies in the browseror even proxy issues. The session functionality obviously also depends on freedisk space & other php.ini settings, etc.)


Chuyên mục: Domain Hosting