PHP 异常错误不起作用


PHP Exception error not working

我有一个非常简单的HTML表单,其中包含用户名,密码和密码确认字段。表单被发送到 PHP 文件进行输入验证。PHP 验证文件实现了异常和 try/catch 块。它目前的工作方式是,如果我提交表单而不输入任何表单字段,它只会在第一个字段上返回错误。id 喜欢它检测所有字段都丢失并针对所有缺少的字段抛出错误。

这是我的 HTML 文件:

<!DOCTYPE html>
<html>
    <head>
        <title>User Registration</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <h3>Register new account</h3>
        <form action="HW4_action_exceptions.php" method="post">
            Username:
            <br/>
            <input type="text" name = "user_name"/>
            <br/>
            Password:
            <br/>
            <input type="password" name ="pass_word" />
            <br/>
            Confirm:
            <br/>
            <input type="password" name = "pass_cfm" />
            <br/>
            <input type="submit" name="register" value="Register">
        </form>
    </body>
</html>

这是我的PHP文件:

<?php
if (isset($_POST['register'])) {

    //put the submitted values into regular variables
    $user_name = $_POST['user_name'];
    $pass_word = $_POST['pass_word'];
    $pass_cfm = $_POST['pass_cfm'];
    //make an array of field names and data types
    $field_names = array("user_name" => "string",
        "pass_word" => "string",
        "pass_cfm" => "string");
    try {
        form_validate($field_names);
    } catch (Exception $e) {
        echo $e->getMessage();
        echo "<br>";
    }
     if (!isset($e) and isset($_POST['register'])) 
     {
        echo "Thanks for your entry. We'll be in touch.";
     }
     else 
     {
        echo "correct form";
     }

}// main if
function form_validate($fns) {
    foreach ($fns as $key => $value) {
        $field_value = $key;
        global $$field_value;
        //echo "actual field value is " . $$field_value . "<br>";   
        switch ($value) {
            Case "string";
                if ((strlen($$field_value) < 1) or ( strlen($$field_value) > 99)) {
                    throw new Exception("Please enter a string value between 1 and 100 characters in the <b>$key</b> field");
                }
                break;
            default;
                break;
        }
    }
}
// test_input
?>

任何帮助,不胜感激。谢谢!

不幸的是,

这不适用于异常。当抛出异常时,捕获块会立即执行,因此后续 try-block 中的所有内容都将被跳过。

您可以尝试使用存储发生的所有错误消息的数组。

$errors = array();
switch ($value) {
  Case "string";
    if ((strlen($$field_value) < 1) or ( strlen($$field_value) > 99)) {
      $errors[] = "Please enter a string value between 1 and 100 characters in the <b>$key</b> field");
    }
    break;
...
}

然后

if (count($errors) == 0 and isset($_POST['register'])) 
 {
    echo "Thanks for your entry. We'll be in touch.";
 }
 else 
 {
    echo "correct form";
 }

我希望这对你有用。