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