PHP Contact From is sending blank emails when the page is viewed

前端 未结 1 386
清歌不尽
清歌不尽 2021-01-29 06:48

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

Here is the code I am using.



        
相关标签:
1条回答
  • 2021-01-29 07:13

    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.

    0 讨论(0)
提交回复
热议问题