Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I appeared for php test, their I was asked one question for which I could not find the answer.

The question is like this.

echo "MESSI is injured!!";
header("Location:somepage.php");

Interviewer want both header and echo to be written on the same page.

I wonder how's it possible.It should give some error like

headers already sent by (output started at .....

Is it really possible to write echo and header onto same page !!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
443 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use Output Buffering as

ob_start();
echo "MESSI is injured!!";
header("Location:somepage.php");
ob_end_flush();

The problem is that we cannot send the header after we start sending the output. To solve this we buffer the output. The function ob_start turns output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. So the echo output will be buffered. Next we send the header without any problem as we've not yet spit out any output. Finally we call ob_end_flush to flush the internal buffer contents and to stop output buffering.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...