質問

I am having difficulties with my php code which validates the form on the page itself before sending out to my email.

This is my PHP which is above the doctype html

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subjectTitle = $_POST['subjectTitle'];
$comment = $_POST['comment'];   
$errormsg = "Invalid Entry";
$validmsg = "Thank you for your message";

if($_POST['submit']) {  
    if(empty($_POST['name'])) {     
        $nameError = true;  
    } 
    if(empty($_POST['email'])) {        
        $emailError = true; 
    }       
    if(empty($_POST['subjectTitle'])) {     
        $subjectError = true;   
    }       
    if(empty($_POST['comment'])) {
        $commentError = true;   
    } 
    else if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['subjectTitle']) || empty($_POST['comment'])) {    
        $error = true;      
    }               
    else {          
        $to = "EMAIL_ADD_GOES_HERE";        
        $name = trim($_POST['name']);
        $email = trim($_POST['email']);
        $subjectTitle = trim($_POST['subjectTitle']);
        $comment = trim($_POST['comment']);         
        $subject = "Contact Form Enquiry";          
        $messages = "\r\n Name: $name \r\n Email: $email \r\n Subject: $subjectTitle \r\n Comments: $comment";
        $headers = "From:" . $name;
        $mailsent = mail($to, $subject, $messages, $headers);       
        if($mailsent) {         
            $sent = true;   
            $name = "";        
            $email = "";
            $subjectTitle = "";
            $comment = "";                          
        }           
    }   
}
?>

and for my HTML , to make viewing easier, I'll just put in the form part.

<html>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
     Name: <input type="text" name="name" id="name" value="<?php echo $name; ?>"> 
     <?php if($nameError == true) {echo $errormsg;} ?>

     Email: <input type="text" name="email" id="email" value="<?php echo $email; ?>"> 
     <?php if($emailError == true) {echo $errormsg;} ?>

     Subject: <input type="text" name="subjectTitle" id="subjectTitle" value="<?php echo $subjectTitle; ?>"> 
     <?php if($subjectError == true) {echo $errormsg;} ?>

     Comments: <textarea name="comment" id="comment"><?php echo $comment; ?></textarea>
     <?php if($commentError == true) {echo $errormsg;} ?>
</form>
</html>

There is no other php code in my html other than stated above.

This validation only works if any field is left empty. It will prompt the error msg within the page itself and would NOT send in the email, which is how it should work..

However, I am facing a weird problem which I can't seem to find out the reason/theory/logic behind it. If u look at the php code, if I didn't have that else if statement

else if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['subjectTitle']) || empty($_POST['comment'])) {        
    $error = true; 
}

the validation fails and will still send in an email when the user keys in the textarea. For example, if the user doesn't fill in the Name, Email and Subject but only the Comments, it will still get sent. However, once i put that else if statement, it fixes the problem.

But the main problem is, preg_match. I want the name fields to allow only space and letters and I want email field to only allow emails. So when I tried to put this code in,

if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
     $nameError = true;
}

or by combing it with the name empty field check

if (empty($_POST['name']) || (!preg_match("/^[a-zA-Z ]*$/",$name))) {
    $nameError = true;      
} 

it doesn't validate correctly. What it does is that, when a user enters a number into the name field and also fills up everything else, it will display error message and also the thank you message and send it to the email, which is not how it should work.

So can I have guidance on how to correct the problem? Is my coding done wrongly and also I would like to know why that else if statement which I have in php makes no sense yet I need that to get the proper validation.

Thank you so much for reading, been stuck on this for the past 6 days and I really dont know how to fix this. Please help me.

Cheers

役に立ちましたか?

解決 2

Try this.

I've made the following changes:

  • Trim the values before validating.
  • Use the variables that were assigned from $_POST in the validation checks.
  • Use a single $error variable that I append errors to.
  • Use + instead of * in the regular expression, so it won't match an empty value, and we don't need an explicit empty() check. Also use the i modifier to make it case-insensitive, instead of A-Za-z.
  • And the most important part: I fixed the else if logic at the end. You were only doing all the empty() checks if the comment wasn't empty.
<?php
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$subjectTitle = trim($_POST['subjectTitle']);
$comment = trim($_POST['comment']);

$errormsg = "Invalid Entry";
$validmsg = "Thank you for your message";
$error = '';

if($_POST['submit']) {

    if(!preg_match('/^[a-z ]+$/i', $name)) {
        $error .= 'Name missing or incorrect<br>';
    } 

    if(empty($email)) {
        $error .= 'Missing email<br>';
    }

    if(empty($subjectTitle)) {
        $error .= 'Missing title<br>';
    }

    if(empty($comment)) {
        $error .= 'Missing comment<br>';
    }

    if ($error) {
        echo $error;       
    } else {
        $to = "EMAIL_ADD_GOES_HERE";

        $subject = "Contact Form Enquiry";

        $messages = "\r\n Name: $name \r\n Email: $email \r\n Subject: $subjectTitle \r\n Comments: $comment";
        $headers = "From:" . $name;
        $mailsent = mail($to, $subject, $messages, $headers);

        if($mailsent) {

            $sent = true;

            $name = "";        
            $email = "";
            $subjectTitle = "";
            $comment = "";

        }

    }

}

?>

他のヒント

change

else if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['subjectTitle']) || empty($_POST['comment'])) {
   $error = true;
}       
else {

to

if (!$nameError && !$emailError && !$subjectError && !$commentError) {

This way the email will only be sent if no error was encountered without re-testing everything.

Alternatively you could set $error = true whenever you set a $xyzError and only test if (!$error) {.

Your first problem is because you never check $nameError or $commentError etc ... You could lose the if statement if you set $error = true; as well or checked all the variables.

(I personally use one $error and then append the message to a single $message variable when doing these sort of things but that's all personal preference)

This is probably the second problem too. You never check $nameError. Also you don't really need the double check if you change your regex to: /^[a-zA-Z]+$/. The + instead of the * says "1 or more characters". * means "0 or more characters".

For email checks use filter_var() with FILTER_VALIDATE_EMAIL. See the docs here: http://php.net/filter_Var

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top