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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!