Interview Question: Can we have an echo before header?

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 !!!

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Solution 2

You can do it as long as all the header calls come before any non-header output is sent (this includes pesky things like newlines/whitespace). So

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

should do the trick

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply