Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Build a Basic PHP Website (2018) Adding a Basic Form Redirection

Ruiqi Mao
Ruiqi Mao
16,675 Points

I don;t understand how will the echo statement before 'header' effect the redirection to a new page;

<?php

echo "some thing to say";

header ("location: thanks.php"); ?>

1 Answer

I'm not sure exactly the mechanics behind it but as soon as you have any output you can no longer use a redirect and instead return an error. That includes echoing anything out as well as including a header after opening HTML tags (inside of a template).

Ruiqi Mao
Ruiqi Mao
16,675 Points

Thanks Corey! Can you explain more about "including a header after opening HTML tags (inside of a template)"?

A lot of times when I'm building something I will make an HTML template that gets included in a file which has some standard formatting. Like opening the html and head tags, meta tags (for charset, http-equiv, viewport, etc.) that are the same across a bunch of files.

But even when you make a template that just has something like so:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

The browser won't show anything and doesn't look like you've done anything. That will still stop you from using header to send the user off somewhere else.

Ruiqi Mao
Ruiqi Mao
16,675 Points

Hi Corey, thanks for your explanation; If I understand correctly, we will have to put the <?php header ("location: other.php"); ?> before the <!DOCTYPE html>......... in order to be able to redirect to another php page?

Exactly. If anything is output to the browser before header it won't work.