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 Redirecting After a Form Submission

I keep getting sent to thanks.php when visiting my site.

I put header("location:thanks.php"); into suggest.php and it automatically send me to thanks.php.

I'm working on Build a Basic PHP Website -> Redirecting After a Form Submission

<?php
$suggest = "home";
$fullname = $_POST["fullname"];
$email = $_POST["email"];
$country = $_POST["country"];

echo "<pre>";
$email_body = "";
$email_body .= "Name: " . $fullname . "\n";
$email_body .= "Email: " . $email . "\n";
$email_body .= "Country: " . $country . "\n";
echo $email_body;
echo "</pre>";

//To do: Send E-mail
header("location:thanks.php");
?>

2 Answers

Zac Mazza
Zac Mazza
5,867 Points

So...

header("location:thanks.php");

does just that. There isn't any other logic set up to prevent you from re-directing automatically. Some form of logic needs to exist, such as a button that calls a function, using JavaScript to redirect using window.href, or using some other method to ensure that the redirect happens only when you want it to.

As the code is right now it gets to the bottom of your script, sees you want to redirect, and takes you to the thanks.php page.

If thanks.php is only sending the e-mail, you could always add it to the bottom of this page instead. It's not outputting any information other than what was carried over from the form. Adding it here would ensure not only is the information displayed, but the e-mail is sent as well.

For that you can either copy the code over directly, or use the php include <file>; syntax to include the actual file.

Hope this helps!

Thanks,

Zac

Jennifer Nordell
Jennifer Nordell
Treehouse Teacher

Hi Zac! I also changed this comment to an answer :sparkles:

Zac Mazza
Zac Mazza
5,867 Points

I need to learn how to do that. :-D