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

Max Carlquist
Max Carlquist
2,791 Points

php contact form not working, http_response_code() not correct aparently. OH NO!

Hey Guys I've followed the blog at http://blog.teamtreehouse.com/create-ajax-contact-form but can't seem to get it to work. I'm not good at php at all and any help would be great!

'''php <?php // My modifications to mailer script from: // http://blog.teamtreehouse.com/create-ajax-contact-form // Added input sanitizing to prevent injection

// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);

    // Check that data was sent to the mailer.
    if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        http_response_code(400);
        echo "Oops! There was a problem with your submission. Please complete the form and try again.";
        exit;
    }

    // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    $recipient = "maximus@tenkaklet.com";

    // Set the email subject.
    $subject = "New contact from $name";

    // Build the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    // Build the email headers.
    $email_headers = "From: $name <$email>";

    // Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // Set a 200 (okay) response code.
        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        echo "Oops! Something went wrong and we couldn't send your message.";
    }

} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

?> '''

2 Answers

Benjamin Payne
Benjamin Payne
8,142 Points

Hey Max, Not sure if you still needed help with this but give the code below this a shot and let me know.

There were a couple of issues with your script I corrected.

filter_var($email, FILTER_VALIDATE_EMAIL)

This returns a string if it validates and false if not, so you can't use the negate operator on it.

Also, you should use set headers and not response codes. http_response_code() only works in 5.4 and greater and while I am all for dropping legacy code, header() works fine.

Let me know if the code below works.

Thanks! Ben

<?php
// Only process POST requests.

if( $_SERVER['REQUEST_METHOD'] !== "POST") {
    header("HTTP/1.0 403 Forbidden");
    echo "There was a problem with your submission, please try again.";
    exit;
}

$name     = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$email    = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$message  = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_FULL_SPECIAL_CHARS);


// Check that data was sent to the mailer.
if ( empty($name) || empty($message) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    // Set a 400 (bad request) response code and exit.
    header("HTTP/1.0 400 Bad Request");
    echo "Oops! There was a problem with your submission. Please complete the form and try again.";
    exit;
}

// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "maximus@tenkaklet.com";

// Set the email subject.
$subject = "New contact from $name";

// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";

// Build the email headers.
$email_headers = "From: $name <$email>";

// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
    // Set a 200 (okay) response code.
    header('HTTP/1.0 200 OK');
    echo "Thank You! Your message has been sent.";
} else {
    // Set a 500 (internal server error) response code.
    header('HTTP/1.0 500 Internal Server Error');
    echo "Oops! Something went wrong and we couldn't send your message.";
}
Stratton Weekley
Stratton Weekley
1,337 Points

This works perfectly! Would there be any security issues to use set headers instead of response codes?