Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Build a Basic PHP Website (2018) Adding a Basic Form Validating Form Data

Steve Fullmer
Steve Fullmer
7,199 Points

Confused: Why does header work if an echo is already sent to the browser first?

So what i've learned is that the header will not work for redirecting if any output is sent to the browser before the header, but yet Alina is echoing $emailbody to the browser and it still works without error. Can anyone explain this? Thanks! :)

if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = $_POST["name"]; $email = $_POST["email"]; $details = $_POST["details"];

echo "<pre>";
$emailbody ="";
$emailbody .= "Name: " . $name . "\n";
$emailbody .= "Email: " . $email . "\n";
$emailbody .= "Details: " . $details . "\n";
echo $emailbody;
echo "</pre>";

//To do: Send email
header("location:suggest.php?status=thanks"); 

}

2 Answers

Hi Steve,

At the time of that recording, I believe that the php environment within workspaces had output buffering turned on. This is why it works out in the video. Instead of the output being sent to the browser, it is stored in a buffer instead and this allows the header redirect to still work.

I believe it has since been turned off. Meaning, the header redirect wouldn't work if you were following along with workspaces. You'd have to comment out the echo statements or turn output buffering back on to get it to work.

Here's some older related questions that might provide you more info:

https://teamtreehouse.com/community/form-redirect-to-thanksphp

https://teamtreehouse.com/community/redirection-to-the-thanksphp-page-is-not-working

They're not necessarily from the same course you're working on but the overall concepts apply.

Thanks for answering that question, Jason. It bothers me that there are some videos where the teachers don't explain something they did behind the scenes. We, as the students, are taking every action they take as Gospel. They can't omit certain parts of the lesson.