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

Anton Moritz
Anton Moritz
5,490 Points

Problem with "Enhancing a simple PHP application" - "Displaying the error message"

Randy Hoyt

I need your help with this. I've followed your code exactly, but I can't get the error message to display properly.

When entering some invalid information in the form, I am instead sent to a blank page.

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$message = trim($_POST["message"]);


if ($name == "" OR $email == "" OR $message == "") {
    $error_message = "You must specify a value for name, email address, and message.";
}

foreach( $_POST as $value ){
    if( stripos($value,'Content-Type:') !== FALSE ){
        $error_message = "There was a problem with the information you entered.";
    }
}

if ($_POST["address"] != "") {
    $error_message = "Your form submission has an error.";
}

require_once("inc/phpmailer/class.phpmailer.php");
$mail = new PHPMailer();

if (!$mail->ValidateAddress($email)){
    $error_message = "You must specify a valid email address.";
}

if(!isset($error_message)){
    $email_body = "";
    $email_body = $email_body . "Name: " . $name . "<br>";
    $email_body = $email_body . "Email: " . $email . "<br>";
    $email_body = $email_body . "Message: " . $message;

    $mail->SetFrom($email, $name);
    $address = "orders@shirts4mike.com";
    $mail->AddAddress($address, "Shirts 4 Mike");
    $mail->Subject    = "Shirts 4 Mike Contact Form Submission | " . $name;
    $mail->MsgHTML($email_body);

    if($mail->Send()) {
        header("Location: contact.php?status=thanks");
        exit;
    }else{
        $error_message = "There was a problem sending the email: " . $mail->ErrorInfo;
    }       
}
}

if(isset($error_message)){
echo $error_message;
}

2 Answers

Try changing this

  if(isset($error_message)){
        echo $error_message;
  }

To this

  if(isset($error_message)){
        echo $error_message;
  } else {
        echo 'Invalid Request';
  }
Randy Hoyt
Randy Hoyt
Treehouse Guest Teacher

Does it work when you enter valid information? Or do you get a blank screen then, also? (The code you pasted above works just fine for me, and I suspect the issue is that the path to the PHPMailer library file is incorrect. If that is indeed the problem, you would get a blank screen with valid data, also.)