Question

I found a PHP script online that isn't working for me while it's nearly identical to others that do work. I just can't seem to get it fixed, here's the one that does work: http://pastebin.com/L1YQ20qf

Also I censored the email and tested it on a PHP supporting webhost, so that can't be the issue. Anyone?

    <?php
if($_POST)
{
    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        die();
    }

    $to_Email       = "censored@myemail.com"; //Replace with recipient email address
    $subject        = 'Contactformulier'; //Subject line for emails

    //check $_POST vars are set, exit if any missing
    if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userMessage"]))
    {
        die();
    }

    //Sanitize input data using PHP filter_var().
    $user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
    $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
    $user_Phone       = filter_var($_POST["userPhone"], FILTER_SANITIZE_STRING);
    $user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);

    //additional php validation
    if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
    {
        header('HTTP/1.1 500 Naam te kort.');
        exit();
    }
    if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
    {
        header('HTTP/1.1 500 Controleer email adres.');
        exit();
    }
    if(!is_numeric($user_Phone)) //check entered data is numbers
    {
        header('HTTP/1.1 500 Alleen nummers als telefoonnummer.');
        exit();
    }
    if(strlen($user_Message)<5) //check emtpy message
    {
        header('HTTP/1.1 500 Bericht te kort.');
        exit();
    }

    //proceed with PHP email.
    $headers = 'From: '.$user_Email.'' . "rn" .
    'Reply-To: '.$user_Email.'' . "rn" .
    'X-Mailer: PHP/' . phpversion();

    @$sentMail = mail($to_Email, $subject, $user_Message .'  -'.$user_Name, $headers);

    if(!$sentMail)
    {
        header('HTTP/1.1 500 Kon het bericht niet verzenden, onze excuses!');
        exit();
    }else{
        echo 'Bericht verzonden!';
    }
}
?>
Was it helpful?

Solution

YOU SHOULD NOT BE USING THE MAIL() FUNCTION

It is very hard to comply with email format RFCs manually using mail(). Instead, update your code to use PHPMailer or a similar library.

Your additional headers variable is incorrect - you must have a Content-type and MIME-Version header:

//proceed with PHP email.
$headers = "From: $user_Email\n" .
"Reply-To: $user_Email\n" .
"MIME-Version: 1.0\n" .
"Content-Type: text/html\n" .
"X-Mailer: PHP/" . phpversion();

$sentMail = @mail($to_Email, $subject, $user_Message .'  -'.$user_Name, $headers);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top