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.

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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀