【问题标题】:PHP form validation using GUMP使用 GUMP 的 PHP 表单验证
【发布时间】:2017-05-04 17:02:44
【问题描述】:

我正在使用 GUMP https://github.com/Wixel/GUMP 进行服务器端表单验证,并且对重定向后显示消息有疑问。

我想在提交后验证表单数据,如果出现错误则重定向到表单,但我不知道在重定向后将错误传递给表单的最佳方式。

我读过这个问题Header Redirect after form Validation in PHP,它提出了两种方法:

1.

$message="Some message for the next page.";
$message=urlencode($message);
header("Location:page.php?message=".$message);

2.

$_SESSION['message']='some other message';

答案的作者认为方法1更安全,但你能告诉我为什么会这样吗?

我也看过php-form-b​​uilder类https://github.com/lkorth/php-form-builder-class是怎么做的,他们好像用的是方法2:

/*Valldation errors are saved in the session after the form submission, and will be displayed to the user
when redirected back to the form.*/
public static function setError($id, $errors, $element = "") {
    if(!is_array($errors))
        $errors = array($errors);
    if(empty($_SESSION["pfbc"][$id]["errors"][$element]))
        $_SESSION["pfbc"][$id]["errors"][$element] = array();
    foreach($errors as $error)
        $_SESSION["pfbc"][$id]["errors"][$element][] = $error;
}

那么,我的问题是,哪种方法最好?使用$_GET 或会话变量传递错误?

附言如果我遗漏了什么,并且有一种更容易/内置于 GUMP 中的方法,请指出!

【问题讨论】:

    标签: php validation redirect


    【解决方案1】:

    两个文件,一个包含所有 PHP 业务逻辑,另一个包含表单(包含在第一个文件中)。第一个文件做了两件事:它检查表单是否已提交并显示表单。在第一次运行时,没有错误消息,因为表单尚未提交。如果表单已提交但未通过验证,请让表单显示错误消息(即:<?php echo $gump->get_readable_errors(true) ?>)。无需在会话中存储错误消息。您还可以使用之前提交的数据重新填充表单。

    form.php

    <?php
    $_error_messages = '';
    if (isset($_POST) && !empty($_POST)) :
        $gump = new GUMP();
        // Let's sanitize the POST data
        $_POST = $gump->sanitize($_POST);
        $gump->validation_rules(array(
             // your validationm rules here
        ));
        $gump->filter_rules(array(
             // your filter rules here
        ));
        // Validate the form data
        $validated_data = $gump->run($_POST);
        if ($validated_data === false) :
            // The submitted data did not validate,
            // display the errors in the form
            $_error_messages = $gump->get_readable_errors(true);
        else :
            // The submitted data validated successfully
            . . .
        endif;
    endif;
    // Display your form
    include 'form-view.php';
    

    form-view.php

    <!DOCTYPE html>
        <html>
        <head>
            // . . .
        </head>
        <body>
            <section>
                <?php echo $_error_messages ?>
                <form
                    action = '<?php echo htmlentities('form.php'); ?>'
                    method = 'post'
                    name   = 'my_form'
                >
                    // The rest of your form here
                </form>
            </section>
        </body>
        </html>
    

    【讨论】:

      猜你喜欢
      • 2016-01-23
      • 2018-06-30
      • 2011-12-02
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      相关资源
      最近更新 更多