donglu9825
donglu9825
2016-12-20 18:30
浏览 41
已采纳

表单验证(PHP)

I need to create validation for this form, and I don't know how to do it right.

    <?php
$errName = '';
$errEmail = '';
$errMessage = '';
$result = '';

if (isset($_POST["submit"])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'simply@email.tld';
    $to = 'again@email.tld';
    $subject = 'Form';

    $body = "Name: $name 
 E-mail: $email 
 Message: $message";
}

if (!$_POST['name']) {
    $errName = 'Write Name here.';
}

if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $errEmail = 'Write correct e-mail';
}

if (!$_POST['message']) {
    $errMessage = 'Write your message';
}

if (!$errName && !$errEmail && !$errMessage) {
    if (mail ($to, $subject, $body, $from)) {
        $result = "<div style='color:white;font-size:15px;font-weight:700;'>Your message has been sent.</div>";
    } else {
        $result = "<div style='color:red;font-size:15px;font-weight:700;'>Your message has not been sent, try again!</div>";
    }

}

?>

The form works right but if as example I won't write one thing there is no error, message just isn't sent. Any ideas what's wrong?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsbj66959
    dsbj66959 2016-12-20 20:04
    已采纳

    The problem I see with your original code is that the variables that contain the error message ($errName, $errEmail, $errMessage) aren't ever echo'd anywhere. They simply get checked if they contain any content and if none of them do then the mail function is called, otherwise nothing.

    I believe a better approach to this would be to use a try/catch block. Your approach continues checking for valid variables even if a previous variable has already failed a check and the mail is already going to be prevented because of it. In this application, a couple extra easy checks aren't going to amount to anything significant, resource-wise. But in a larger application it's a good idea to not waste resources if you already know something is going to fail.

    I've rewritten your code using the suggested try/catch block.

    <?php
    
    if (isset($_POST["submit"])) {
    
        $name       = (string) $_POST['name'];
        $email      = (string) $_POST['email'];
        $message    = (string) $_POST['message'];
    
        $from       = 'simply@email.tld';
        $to         = 'again@email.tld';
        $subject    = 'Form';
    
        $body = "Name: $name 
     E-mail: $email 
     Message: $message";
    
        try {
    
            if (!$name) {
    
                throw new Exception('Write Name here.');
    
            }
    
            if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    
                throw new Exception('Write correct e-mail');
    
            }
    
            if (!$message) {
    
                throw new Exception('Write your message');
    
            }
    
            if (mail ($to, $subject, $body, $from)) {
    
                $result = "<div style='color:white;font-size:15px;font-weight:700;'>Your message has been sent.</div>";
    
            } else {
    
                throw new Exception("Your message has not been sent, try again!");
    
            }
    
        } catch(Exception $e){
    
            $result = "<div style='color:red;font-size:15px;font-weight:700;'>" . $e->getMessage() . "</div>";
    
        }
    
        echo $result;
    
    }
    
    ?>
    

    If a variable doesn't pass one of your checks, a new Exception is thrown with the applicable error message. This stops further execution in the try block and moves execution to the catch block. The $result variable gets filled with your styled error message, which gets echo'd at the end. Likewise, if the mail is successfully sent, the $result variable gets filled with the success message which gets echo'd.

    点赞 评论

相关推荐