简体   繁体   中英

My php validation and form to email go straight to my confirmation page

I have a form, php validation, and send to email. My php validation works fine. My send to email works fine. When I use them both together, they work fine until I add header('Location: http://google.com '); exit(); I am using google.com for because I havent made my confirmation page yet. When I add this line to the php, that's when it goes straight to google.com when I go to my website. Can someone please help? I have been trying to figure out all of this validation and form to email for 2 straight days now, and I cannot figure it out. I know nothing about php. My code is below.

My php:

<?php

// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";

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["email2"])) {
        $email2Err = "It is required to re-enter your email.";
    } else {
        $email2 = test_input($_POST["email2"]);
        // check if e-mail address syntax is valid
        if ( ! preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email2)) {
            $email2Err = "Invalid email format"; 
        }
    }
    if (empty($_POST["comments"])) {
        $commentsErr = "A comment is required.";
    } else {
        $comments = test_input($_POST["comments"]);
        if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) {
            // Everything ok. Do nothing and continue 
        } else { 
            $commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _                   / ' ! £ $ % * () + = - Only";  
        }
    }
    if (isset($_POST['service'])) {
        foreach ($_POST['service'] as $selectedService)
            $selected[$selectedService] = "checked";
    }
}
if (empty($errors)) { 
    $from = "From: Our Site!"; 
    $to = "jasonriseden@yahoo.com"; 
    $subject = "Mr Green Website | Comment from " . $name . "";

    $message = "Message from " . $name . " 
      Email: " . $email . " 
      Comments: " . $comments . "";
    mail($to, $subject, $message, $from);
    header('Location: http://google.com');
    exit();
}
?>

Please someone help me. I have no idea what is wrong.

Ok. I did what you told me Barmar. Not sure if I did it right or not. It solved one problem, but another was created.

I started over with the code that validates and sends the form data to my email. Now I just want to add header('Location: http://google.com '); exit(); ....and it work. Can you tell me what to do? I have no idea what php, so the more specific that you can be, the better.

Here is the php:

<?php

// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";

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["email2"]))
     {$email2Err = "It is required to re-enter your email.";}
   else
     {$email2 = test_input($_POST["email2"]);
     // check if e-mail address syntax is valid
    if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email2))
      {
      $email2Err = "Invalid email format"; 
      }
    }

    if (empty($_POST["comments"]))
     {$commentsErr = "A comment is required.";}
   else
     {$comments = test_input($_POST["comments"]);
      if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) { 
        // Everything ok. Do nothing and continue 
    } else { 
        $commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _ / ' ! £ $ % * () + = - Only";  
      }
    }
     if (isset($_POST['service']))
    {
        foreach ($_POST['service'] as $selectedService)
            $selected[$selectedService] = "checked";
    }

}

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

if (empty($errors)) { 
  $from = "From: Our Site!"; //Site name
  // Change this to your email address you want to form sent to
  $to = "jasonriseden@yahoo.com"; 
  $subject = "Mr Green Website | Comment from " . $name . "";

  $message = "Message from " . $name . " 
  Email: " . $email . " 
  Comments: " . $comments . "";
  mail($to,$subject,$message,$from);

  }
?>

The problem is that there's no variable $errors . So if(empty($errors)) is always true, so it goes into the block that sends email and redirects. This happens even if the user hasn't submitted the form yet -- I'm assuming this code is part of the same script that displays the registration form after the code you posted.

You need to make two changes:

  1. The code that sends the email and redirects should be moved inside the first if block, after all the validation checks.

  2. Instead of if(empty($error)) , it should check if($nameErr && $emailErr && $email2Err && $commentsErr) . Or you should change the validation code to set $error whenever it's setting one of these other error message variables.

I know this isn't a direct answer to your question, but have a look into Exceptions . By having seperate functions for each validation and have them throw an exception when something is wrong, your code will be much cleaner and bugs will have much less room to pop up. Bonus points if you put all the validation functions in a class.

Example: (I renamed test_input() to sanitize_input(), because that's what it does)

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    try
    {
        $name = getValidatedName();
        $email = getValidatedEmail();

        // send email with $name and $email
    }
    catch (Exception $e)
    {
        echo '<div class="error">' . $e->getMessage() . '</div>';
    }
}

function getValidatedName()
{
    if (empty($_POST["name"]))
        throw new Exception("Name is required");

    $name = sanitize_input($_POST["name"]);

    if (!preg_match("/^[a-zA-Z ]*$/", $name))
        throw new Exception("Only letters and white space allowed");

    return $name;
}

function getValidatedEmail()
{
    if (empty($_POST["email"]))
        throw new Exception("Email is required");

    $email = sanitize_input($_POST["email"]);

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // you don't have to reinvent the wheel ;)
        throw new Exception("Invalid email format");

    return $email;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM