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

Problem with Contact form when going through the "Working with Get Variables" video.

Hello there guys,

I've been following the 'Build a Simple PHP Application' and I've come to a halt and I don't have a clue what I'm doing wrong.

So, the video I'm onto is the 'Working with Get Variables', I tried creating my own Contact form to see if I could use this method of working with forms (i.e it redirects to the same page) with any form. Heres the code:

<!DOCTYPE html>
<html>
<head>
    <title>Contact form test</title>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $surname = $_POST["surname"];
    $email_body = "";
    $email_body = $email_body . "Name: " . $name . "\n";
    $email_body = $email_body . "Surname: " . $surname;

    header("Location: contact.php?status=thanks");
    exit;
}
?>

<?php if (isset($_GET["status"]) AND $_GET["status"] == "thanks") { ?>
    <p>ITS WORKING, ITS WORKING!!!1</p>
<?php } else { ?>
    <form method="post" action="contact.php">
        <input type="text" name="name" placeholder="name" id="name">
        <input type="text" name="surname" placeholder="surname" id="surname">
        <input type="submit" value="Send">
    </form>
<?php } ?>

</body>
</html>

The problem is that when I click submit, it brings be to an empty page. Any clues?

Thanks in advanced, Luke

2 Answers

I c/p'd your snippet and it worked for me locally, but refer to Randy's answer for best practice.

Randy Hoyt
STAFF
Randy Hoyt
Treehouse Guest Teacher

The block of PHP code must come before any HTML. There shouldn't be anything (not even a space!) before this block:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $surname = $_POST["surname"];
    $email_body = "";
    $email_body = $email_body . "Name: " . $name . "\n";
    $email_body = $email_body . "Surname: " . $surname;

    header("Location: contact.php?status=thanks");
    exit;
}
?>

The redirect is handled by calling the header function. You must set headers with this function before any content. If you try to call header after any HTML, like you are doing now, you will get a fatal error.

Does that help?

Thanks for your help Randy, that helped. Couldn't think for the life of me what was wrong... silly mistakes eh :D

Luke