Search code examples
phpemailmessageconfirmation

PHP Mailer: Specific Confirmations Messages based on Empty Fields


I have a Contact Form which submits the data using AJAX to a PHP mailer. Once the email have been sent a confirmation message is shown to the user. It works well. My problem is how to customize the confirmation message based on which fields have been filled.

The form has four fields. Name (required), Subject (option list: by default 'Subscribe to Newsletter'), Email (required) and Message and there are two cases:

1) User is only looking to get subscribed to the Newsletter. Only 'Name' and 'Email' fields are filled. Confirmation message A.

2) User sends an email. 'Name', 'Email' and 'Message' are filled. Confirmation message B.

This is my current code, shows a general confirmation message:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = strip_tags(trim($_POST["name"]));
    $asunto = strip_tags(trim($_POST["asunto"]));
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);

    if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo "¡Error 400 bla bla...! 
        exit;
    }

    $recipient = "[email protected]";
    $subject = "Nauta $name";
    $email_content = "Nombre: $name\n";
    $email_content = "Asunto: $asunto\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Mensaje:\n$message\n";
    $email_headers = "From: $name <$email>";

    if (mail($recipient, $subject, $email_content, $email_headers)) {
        http_response_code(200);         
        echo "¡Thank you! bla bla...";
    }
    else {
        http_response_code(500);
        echo "¡Error 500 bla bla...! 
    }
}
else {
    http_response_code(403);
    echo "¡Error 403 bla bla...!
}

I tried the following structure (elseif) with no luck.

if ( ) {
   echo "...";
} elseif ( ) {
   echo "...";
} else {
   echo "...";
}

No results.


Solution

  • Try to ask if message is an empty string or one blank character:

    if  ($_POST['message']!="") {
        ...
    }