-1

Can anyone help me stop blank emails from being sent each time the page is viewed?

Here is the code I am using.

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr  = "";
$name = $email = $gender = $comment =  "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (empty($_POST["name"])) {
     $nameErr = "Name is required";
   } else {
     $name = test_input($_POST["name"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
       $nameErr = "Only letters and white space allowed"; 
     }
   }

   if (empty($_POST["email"])) {
     $emailErr = "Email is required";
   } else {
     $email = test_input($_POST["email"]);
     // check if e-mail address syntax is valid
     if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
       $emailErr = "Invalid email format";
     }
   }

   if (empty($_POST["comment"])) {
     $commentErr = "Comment is required";
   } else {
     $comment = test_input($_POST["comment"]);
     if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
       $commentErr = "Please leave a comment.";      
     }
   }
}

function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}


//create the body of the email
$body = "Name: {$_POST['name']}
\n\nEmail: {$_POST['email']}
\n\nComments: {$_POST['comment']}";
$body = wordwrap($body, 70);

// The mail function
mail('email@email.com', 'Contact Us Submission', $body, "From: {$_POST['email']}");


?>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
   Name: <input type="text" name="name" class="text" value="<?php echo $name;?>">
   <span class="error">* <?php echo $nameErr;?></span>
   <br>
   Email: <input type="text" name="email" class="text" value="<?php echo $email;?>">
   <span class="error">* <?php echo $emailErr;?></span>
   <br>
   Comment: <textarea name="comment" rows="3" cols="20"><?php echo $comment;?></textarea>
   <span class="error">* <?php echo $commentErr;?></span><br>   
   <input type="submit" name="submit" value="Submit" class="submit"> 
<?php
//if everything is ok, print the message:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($name && $email && $comment) {
    echo "<p>Thank you, <b>$name</b>, for contacting us.</p>
    <p> We will email you back at <i>$email</i> in a couple days.</p>\n";
} else { //missing form value.
    echo '<p class="error">Please go back and fill out the form again.</p>';
    return false;
}
}

?>
</form>
Pedro del Sol
  • 2,840
  • 9
  • 39
  • 52
  • Are all of your $_POST values being passed correctly? – WillardSolutions Jul 22 '14 at 15:04
  • Instead of (the first) `if ($_SERVER["REQUEST_METHOD"] == "POST")` you can do `if(isset($_POST['submit']))` that will only execute your code if the submit button was pressed. Plus, check for empty values etc. or use 2 seperate pages along with my suggestion along with a header. – Funk Forty Niner Jul 22 '14 at 15:05
  • From w hat I can see your `mail();` function is not placed in any braces, so will always be ran when someone browses the page. The answer by @JohnConde will give the best solution. – Daryl Gill Jul 22 '14 at 15:08
  • All the $-POST values are being passed correctly. I will try the if(isset$-POST['submit'])) instead of what I have. I didn't think about adding the mail(); function inside of braces. I will also try that too. Thank you all! – Gloria E Jul 22 '14 at 18:17

1 Answers1

3

Put all of your form logic inside of your if ($_SERVER["REQUEST_METHOD"] == "POST") { statement. Not just the validation:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (empty($_POST["name"])) {
     $nameErr = "Name is required";
   } else {
     $name = test_input($_POST["name"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
       $nameErr = "Only letters and white space allowed"; 
     }
   }

   if (empty($_POST["email"])) {
     $emailErr = "Email is required";
   } else {
     $email = test_input($_POST["email"]);
     // check if e-mail address syntax is valid
     if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
       $emailErr = "Invalid email format";
     }
   }

   if (empty($_POST["comment"])) {
     $commentErr = "Comment is required";
   } else {
     $comment = test_input($_POST["comment"]);
     if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
       $commentErr = "Please leave a comment.";      
     }
   }


    //create the body of the email
    $body = "Name: {$_POST['name']}
    \n\nEmail: {$_POST['email']}
    \n\nComments: {$_POST['comment']}";
    $body = wordwrap($body, 70);

    // The mail function
    mail('email@email.com', 'Contact Us Submission', $body, "From: {$_POST['email']}");
}

FYI, you are wide open to header injections. That's something you should address before publishing this code to production.

Community
  • 1
  • 1
John Conde
  • 217,595
  • 99
  • 455
  • 496