miatech
miatech

Reputation: 2278

not getting emails from my php contact form

I have a contact.html form that submits fields to contact.php script; however, I'm not getting the emails on my inbox. yes the to: email address is correct. here the address to the form web page here's the code for contact.php

<?php

    $my_email = "[email protected]";
    $final_msg = "";

    //validation function
    function validate($data) {
        $data = trim($data); //removing white space and tabs
        $data = stripslashes($data); //removing \
        $data = htmlspecialchars($data); //converting to html
        return $data;
    }

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

    }
    $final_msg += "name: " . $name . "\n" .
                 "email: " . $email . "\n" .
                 "subject: " . $subject . "\n" .
                 "message: ". $message;

    $headers = "From: [email protected] \r\n" . "Reply-To: " . $email . "\r\n";

    if(mail($my_email, $subject, $final_msg, $headers)) {
        echo "<b>Your Message Was Successfuly Sent!... Thanks</b>" . "<br>";
        echo "<b>name: </b>" . $name . "<br>";
        echo "<b>email: </b>" . $email . "<br>";
        echo "<b>subject: </b>" . $subject . "<br>";
        echo "<b>message: </b>" . $message;
    }
    else {
        echo "<b>Your Message Could not be Sent!... Sorry</b>";
    }


?>

Upvotes: 1

Views: 53

Answers (1)

pavel
pavel

Reputation: 27092

You use bad concatenating operator.

The correct one for strings is .=, not +=.

$final_msg .= '...';

Then, everything should be in condition if the form was sent. Now you try to send mail every time the script is loaded, independing on the fact the form was (successfully) sent.

if($_SERVER['REQUEST_METHOD'] == "POST") {
    // sanitize form data, prepare $headers, $final_msg here
    if (mail(...)) {
        ...
    } else {
        ...
    }
}

The condition should be

if (filter_var($_POST['mail'], FILTER_VALIDATE_EMAIL) &&
    !empty($_POST['name']) && 
    !empty($_POST['subject']) &&
    !empty($_POST['message'])
) {
    //
} else {
    // incomplete form was sent, or data are incorrect
}

insteda of if($_SERVER['REQUEST_METHOD'] == "POST") {

Upvotes: 1

Related Questions