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 Simple PHP Application Adding a Contact Form Working with Get Variables

why doesnt it work?

Hello

1) when I run the code, click on the contact link, without fillout out the form, I press submit, I still get the "Thanks for the email! I'll be in touch shortly! " message. In fact the else form never runs, why is that?

  <?php if (isset($_GET["status"]) AND $_GET["status"] == "thanks") { ?>
                <p>Thanks for the email! I&rsquo;ll be in touch shortly!</p>
            <?php } else { ?>

2) In the if(){}else{}, I don't understand why we break the <?php...?> in such a way. Shouldn't the php block statement wrap around the whole if clause from If() to after the thanks message, and shouldn't the else start from the <?php else all the way to the end of the form <?>

<?php 

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $email =  $_POST["email"];
    $message =  $_POST["message"];
    $email_body = "";
    $email_body = $email_body . "Name: " . $name . "\n";
    $email_body = $email_body . "Email: " . $email . "\n";
    $email_body = $email_body . "Message: " . $message;

    // TODO: Send Email

    header("Location: contact.php?status=thanks");
    exit;
}
?><?php 
$pageTitle = "Contact Mike";
$section = "contact";
include('inc/header.php'); ?>

    <div class="section page">

        <div class="wrapper">

            <h1>Contact</h1>

            <?php if (isset($_GET["status"]) AND $_GET["status"] == "thanks") { ?>
                <p>Thanks for the email! I&rsquo;ll be in touch shortly!</p>
            <?php } else { ?>

                <p>I&rsquo;d love to hear from you! Complete the form to send me an email.</p>

                <form method="post" action="contact.php">

                    <table>
                        <tr>
                            <th>
                                <label for="name">Name</label>
                            </th>
                            <td>
                                <input type="text" name="name" id="name">
                            </td>
                        </tr>
                        <tr>
                            <th>
                                <label for="email">Email</label>
                            </th>
                            <td>
                                <input type="text" name="email" id="email">
                            </td>
                        </tr>
                        <tr>
                            <th>
                                <label for="message">Message</label>
                            </th>
                            <td>
                                <textarea name="message" id="message"></textarea>
                            </td>
                        </tr>                    
                    </table>
                    <input type="submit" value="Send">

                </form>

            <?php } ?>

        </div>

    </div>

<?php include('inc/footer.php') ?>

9 Answers

Hugo Paz
Hugo Paz
15,622 Points

Hi orange sky,

The else does work, if not when you go to the contact page you would not see the form.

You get the message because there is no validation at this stage.

An easy way to see that in action is to go to your form and add 'required' in all your fields.

like this

<input type="text" name="name" id="name" required>

<input type="text" name="email" id="email" required>

<textarea name="message" id="message" required></textarea>

will try it right now, Thanks Hugo!

Hugo Paz
Hugo Paz
15,622 Points

When you click the url to the contact page and when you are redirected to it this code fails:

if ($_SERVER["REQUEST_METHOD"] == "POST") 

because the request method is 'GET'.

Here is a easy way to check this out:

add this line of code just below the div with the class of wrapper:

<?php echo $_SERVER["REQUEST_METHOD"]; ?>

OMG, you right!

But why would the request method be 'GET' when I click on the contact link? I mean the form method says 'post' so what causes it to change to get.

thansk

Hugo Paz
Hugo Paz
15,622 Points

Post is used to send the form, the contact page is loaded again and this code runs

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $email =  $_POST["email"];
    $message =  $_POST["message"];
    $email_body = "";
    $email_body = $email_body . "Name: " . $name . "\n";
    $email_body = $email_body . "Email: " . $email . "\n";
    $email_body = $email_body . "Message: " . $message;

    // TODO: Send Email

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

at the end you have an header, this redirects the current page to whatever url is specified, in this case 'contact.php?status=thanks'. This redirects uses the get method.

So to recapitulate, when you send the form, you use the post method, the contact page is loaded, the code on the top runs and the contact page is loaded again, this time using the get method, displaying the thank you message.

Roberto Alicata
PLUS
Roberto Alicata
Courses Plus Student 39,959 Points

When you submit the form (compiled or blank) the form action recall the page with the POST method.

In the top of the code there is an if statement

if ($_SERVER["REQUEST_METHOD"] == "POST") {
............
    header("Location: contact.php?status=thanks");
    exit;
}

The page receives a POST as $_SERVER["REQUEST_METHOD"] so it changes the header location to contact.php?status=thanks" and in the if statement

            <?php if (isset($_GET["status"]) AND $_GET["status"] == "thanks") { ?>
                <p>Thanks for the email! I&rsquo;ll be in touch shortly!</p>
            <?php } else { ?>
            ............
            <?php } ?>

it chooses the first condition.

Hello Roberto,

Thansk for the detailed explanation. Using th same scenario or the given, could the else {} run.

If it can't run, as is the current case, then why create an else block.

thanks!

Hello Hugo,

You are right, the else does work, but now I am confused as to the order of the if () {} else{}

Let me try to reason the process on own:

1) When I run the code, land on index.php, and press the contact link in the navigation bar, It calls the contact.php page.

2) In the contact.php, there is some php so before the server serves up this page, it processes it. At this stage it should first process the first line which is

if ($_SERVER["REQUEST_METHOD"] == "POST") {.... , Since this is true, it should execute the header() and send the status=thanks in the url as its returns the contact page. I guess before it returns the contact.page to the browswer, (since everything is being done on the same page which is contact.php) it should right then and there evaluate the if( isset($_GET['status']) AND $_GET['status']=="thanks"), which in my opinion is always true, because we have set the value of the variable status to thanks in header(). Is seems to me there is no way for the form to ever show, but it does. Whre am I going wrong?

Thanks!

Right on!!!!

But just one thing, Remember that we are on index.php, and we are about to click the contact link in the navigation bar, so would you still consider "clicking on the contact link in the index.php file " as sending a form, even thou there is no form visible then.

"So to recapitulate, when you send the form, you use the post method, the contact page is loaded, the code on the top runs and the contact page is loaded again, this time using the get method, displaying the thank you message."

Big Thanks!!!

Hugo Paz
Hugo Paz
15,622 Points

Sending the form only happens when you click on the submit button in the form. So when you click on any link to the contact page you do not send any form.

Im sorry Hugo,

So if we were to consider this whole process from clicking on a link in the index.php, how would you rephrase the first line of your explanation:

"So to recapitulate, when you send the form, you use the post method, the contact page is loaded, the code on the top runs and the contact page is loaded again, this time using the get method, displaying the thank you message."

Cheers!

Hugo Paz
Hugo Paz
15,622 Points

You click on the contact page link on index.php -> get method

You submit the form on the contact page, clicking the submit button -> post method

The code at the top of the contact page runs, the page is redirected -> get method

Oh, so should I assume that whenever I click on a link, that is connected to a form, no matter what the method of the form, the form will always take on a get method, because I clicked on a link to get to the form?

Hugo Paz
Hugo Paz
15,622 Points

No.

The form only runs if you click on its submit button. The fact that you go to a page that has a form does not mean that the form will run.

Ok, the form does not run, but when I click on the link in index.php ...

Wait, are we saying that when we click on the link in index.php, the form naturally appears, because of the <a href="contact.php"> without evaluting the if($_SERVER){}..... So The only time $($_SERVER ..) gets considered is when we click the submit button?

Hugo Paz
Hugo Paz
15,622 Points

Yes. You are correct.

Hello!

I put it all together:

1) When you click on the link called 'contact from the index.php file, the form appears because the else ( if($_GET['status']...){} else{}) clause evaluates to true( by nature, a click on any link causes the "GET" method to execute)

2) Wheter we fill out the form or not, once we press the submit button, the if($_SERVER['REQUEST_METHOD)=="POST"){...} gets executed and as per the header('Location:contact.php?status=thanks') , the contact.php form gets called and a variable(status) and a value (thanks) get sent along with the request for the contact.php form.

3) When sending a variable and a value along with a request for a form, the method changes to Get automatically, thus the if($_GET['status']=="thanks").. evaluates to true in this case, because the variable and value sent by the header() evaluated to true; finally the Thank you message appears.

Thank you Hugo for the bits and pieces that helped me put it together!