Search code examples
phpemailcontactscontact-form

PHP contact form sending multiple emails when I add $headers


I have a contact form which sends emails but displays my email server as the "from" and hence it is difficult to reply to emails sent from the contact form

I have tried adding

$headers = 'Reply-To: ' . $email . "\r\n" . 'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);

to my script but although this works perfectly in respect to sending an email you can reply to, it still also sends an email which you cannot reply to!

I am a PHP newbie so I think I have made an error making two messages send, if someone could please point out what it is that would be much appreciated as although I have looked at other similar questions on here I cannot find a solution

Here is my code:

include ("includes/header.php");
$pagetitle   = "Contact Us";
$description = "";
$keywords    = "";
$name        = ($_POST['name']);
$email       = ($_POST['email']);
$message     = ($_POST['message']);
$from        = ($_POST['email']);
$to          = '[email protected]'; 
$subject     = "Enquiry from Visitor " . $name;
$human       = ($_POST['human']);
$headers     = 'Reply-To: ' . $email . "\r\n" . 'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>

<div class="container-fluid contactform">
   <div class="col-md-6 contactform-padding">   
     <h2>Contact Us</h2>

<?php 
    if (isset($_POST['submit']) && $human == '4') {              
      if (mail ($to, $subject, $body, $from)) { 
         echo '<p>Thanks for getting in touch. Your message has been sent & We will get back to you shortly!</p>';
       } else { 
          echo '<p>Something went wrong, go back and try again!</p>'; 
       }  
    } else if (isset($_POST['submit']) && $human != '4') {
       echo '<p>You answered the anti-spam question incorrectly!</p>';
    }
?>

 <form method="post" action="index.php" data-ajax="false" method="POST" enctype="multipart/form-data">
 <div class="form-group">
  <label class="control-label " for="name">
   <p>Name</p>
  </label>
  <input class="form-control" id="name" name="name" type="text"/>
 </div>

Please could someone point out to me why this is sending two emails? I would REALLY appreciate it - I know I have made a stupid mistake and I cannot see why/how

Thanks!


Solution

  • Please check code once again.

    You are calling mail function two times. One in above and another in if condition

    from above code remove the mail function

    mail can be sent from your if condition