开发者

PHP "Cannot modify header information" [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Headers already sent by PHP

I've been using the header("Location: ..") command everwhere in my PHP files. Usually, I would run several checks (if / else) and then simply redirect the user if all the info is correct or send them somewhere else if it isn't.

Header has been used even after I echoed and in between html tags. Everything worked. I never knew there were limitations anyway, I thought I can use it everywhere..

Today I fiddled around a bit with the header tags and suddenly those warning messages kept popping up in my log files and things stopped working.

So I have two questions:

1) What is the correc开发者_开发知识库t approach to serving the correct views? Should I rather conditionally include PHP HTML code in the same file?

2) Why does it work in some cases? For example I have my logginIn() function which is called AFTER html and input fields etc have already been shown.. yet it works.


1) Check everything you need before actually outputting your code, or use manual output buffering

<?php
ob_start();
echo "hello";
ob_end_flush();
header("Location:http://stackoverflow.com"); // redirects you

or even worse solution, turn on output_buffering (php.ini).

2) So you've probably got output_buffering turned on


Try using output buffering.

A quick example:

<?php
ob_start();

// ... some more code ...
header("Location: www.google.com");

echo 'something';

ob_end_flush();


I have written a complete solution to this problem at http://digitalpbk.com/php/warning-cannot-modify-header-information-headers-already-sent. Hope it addresses everyones issues with headers and cookies.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜