Php header() function example

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

Warning: Cannot modify header information - headers already sent by (output started at /some/file.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: Php header() function example

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


No output before sending headers!

Functions that send/modify HTTP headers must be invoked before any output is made.summary ⇊Otherwise the Hotline 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:

Unintentional:

Whitespace before or after ?>Previous error messages or notices

Intentional:

print, eđến và other functions producing outputRaw sections prior code.

Why does it happen?

To underst& why headers must be sent before output it"s necessaryto look at a typical HTTPresponse. PHPhường scripts mainly generate HTML content, but also pass amix 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...

and

The page/output always follows the headers. PHP has khổng lồ pass theheaders lớn the webVPS first. It can only bởi vì that once.After the double linebreak it can nevermore amend them.

When PHPhường receives the first output (print, echo, ) 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.phpvà line 52. That"s where you had khổng lồ look for premature output.

Typical causes:

Print, echo

Intentional output from print & echo statements will terminate the opportunity to sover HTTPhường 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_rreadtệp tin, passthru, flush, imagepng, imagejpeg

amuốn others & user-defined functions.

Raw HTML areas

Unparsed HTML sections in a .php tệp tin are direct output as well.Script conditions that will trigger a header() Gọi must be notedbefore any raw blocks.

Use a templating scheme khổng lồ separate processing from output logic.

Place khung processing code atop scripts.Use temporary string variables lớn defer messages.The actual output súc tích and intermixed HTML output should follow last.

Xem thêm: Cách Chuyển Host Cho Website Wordpress Sang Hosting Mới? Hướng Dẫn Chuyển Host Cho Wordpress

Whitespace before for "script.php line 1" warnings

If the warning refers to lớn 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:

?>PHPhường. actually eats up a single linebreak after cđại bại 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 PHPhường startup/warning message.

No error message

If you have 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.

Output đầ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 controlxúc tích và ngắn gọn. Its actual purpose is minimizing chunked transfers to lớn the webVPS.

It can likewise be engaged with a điện thoại tư vấn to 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 to send 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, and 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 VPS.

Checking with headers_sent()

You can always use headers_sent() to probe ifit"s still possible lớn... send headers. Which is useful to conditionally printinfo or apply other fallback ngắn gọn xúc tích.

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

HTML tag

If your application is structurally hard to 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 khổng lồ non-valid HTML when utilized past the section.Most browsers still accept it.

Xem thêm: Serial Number Key Idm 6 - Internet Download Manager (Idm) 6

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() và session_start() need khổng lồ 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 and other php.ini settings, etc.)


Chuyên mục: Theme wordpress