Search code examples
phpformsajaxform

How do I fix this undefined variable error for a php contact form?


I'm getting blank emails everyday in around the same hour, and getting undefined variable error in my php mailer, what do I need to do to fix it? I have in my page 2 different forms.

I tried to add this to my php: if (isset($_POST)){}, After I add it I still got blanks but the error now is for different line. Now my error is for the $email_subject $email_body lines 35,36.

This is the error log:

[19-Sep-2019 19:26:50 UTC] PHP Notice: Undefined variable: name in /home/user/public_html/mail/mailer.php on line 35 [19-Sep-2019 19:26:50 UTC] PHP Notice: Undefined variable: name in /home/user/public_html/mail/mailer.php on line 36

My PHP:

if (isset($_POST['name'])) {
    $name = $_POST['name'];
}

if (isset($_POST['fname'])) {
    $fname = $_POST['fname'];
}

if (isset($_POST['lname'])) {
    $lname = $_POST['lname'];
}

if (isset($_POST['email'])) {
    $email = $_POST['email'];
}

if (isset($_POST['tel'])) {
    $tel = $_POST['tel'];
}

if (isset($_POST['address'])) {
    $address = $_POST['address'];
}

if (isset($_POST['project'])) {
    $project = $_POST['project'];
}

if (isset($_POST['message'])) {
    $message = $_POST['message'];
}

    $to = '';
    $email_subject = "$fname $lname $name Contact You from :";
    $email_body = "You have received a new message from your website contact form.<br/>"."Here are the details:<br/><br/> Name: $fname $lname $name<br/> Email: $email<br/> Phone: $tel<br/> Address: $address<br/> Project: $project<br/> Message:\n$message";
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= 'From: ' . "\r\n";
    $headers .= 'Reply-To: ' . "\r\n";
    $headers .= 'X-Mailer: PHP/' . phpversion();
    $name = $fname = $lname = $email = $tel = $address = $project = $message = '';

    if(mail($to,$email_subject,$email_body,$headers)) {
            echo "OK";
        }

Solution

  • Without seeing the error message I would guess that not all fields are being filled out so you'll want to default those variables before checking if they are set:

    $name = $fname = $lname = $email = $tel = $address = $project = $message = '';