How to fix “cannot modify header information” in wp

This question's answers are a community effort. Edit existing answers khổng lồ improve sầu 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/file.php:12) in /some/file.php on line 23

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

Bạn đang xem: How to fix “cannot modify header information” in wp

What could be the reason for this? And how khổng lồ fix it?

No output before sending headers!

Functions that send/modify HTTPhường 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:

đầu ra can be:


Whitespace before or after ?>Previous error messages or notices


print, echo và other functions producing outputRaw sections prior code.

Why does it happen?

To understvà why headers must be sent before output it"s necessarylớn look at a typical HTTPresponse. PHP. scripts mainly generate HTML content, but also pass aphối of HTTP/CGI headers 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 lớn pass theheaders lớn the webVPS first. It can only do that once.After the double linebreak it can nevermore amover them.

When PHP receives the first output (print, emang đến, ) it willflush all collected headers. Afterward it can skết thúc all the outputit wants. But sending further HTTP 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 to 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.php& line 52. That"s where you had to lớn look for premature output.

Typical causes:

Print, echo

Intentional output from print and emang đến statements will terminate the opportunity to lớn send HTTP. headers. The application flow must be restructured to lớn 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

amuốn others và 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() Call must be notedbefore any raw blocks.

Use a templating scheme lớn separate processing from output ngắn gọn xúc tích.

Place size processing code atop scripts.Use temporary string variables lớn defer messages.The actual output ngắn gọn xúc tích và intermixed HTML output should follow last.

Xem thêm: Troubleshooting Http Error 500, Troubleshooting: Http Error 500 (Or 500

Whitespace before for "script.php line 1" warnings

If the warning refers khổng lồ 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 into such gaps.

Error source mentioned as "Unknown on line 0"

It"s typically a PHP.. 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 lớn 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.

đầu ra buffering as a workaround

PHPs output bufferingis a workaround to alleviate this issue. It often works reliably, but shouldn"tsubstitute for proper application structuring and separating output from controlsúc tích. Its actual purpose is minimizing chunked transfers to the webVPS.

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 xúc tích và ngắn gọn attempts lớn sover binary content (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, và for more pros và 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 hệ thống.

Checking with headers_sent()

You can always use headers_sent() lớn probe ifit"s still possible lớn... sover headers. Which is useful khổng lồ conditionally printinfo or apply other fallbaông xã xúc tích.

if (headers_sent()) die("Redirect failed. Please cliông xã 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 khổng lồ allow redirects is injecting a HTML tag. A redirect can be achieved with:

Or with a short delay:

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

Xem thêm: Hướng Dẫn Cách Thay Đổi Ảnh Thumbnail Video Trên Facebook Video

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

Why setcookie() and session_start() are also affected

Both setcookie() and session_start() need lớn skết thúc a Set-Cookie: HTTPhường header.The same conditions therefore apply, & 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 và other php.ini settings, etc.)

Chuyên mục: Kiến thức Hosting