2017-05-04 77 views
0

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

我想在提交后验证表单数据,然后在出现错误时重定向到表单,但我不知道在重定向之后将错误传递到表单的最佳方法。

我读过这个问题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的形式,器类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或在会话变量中传递错误?

p.s.如果我错过了某些东西,并且有一种方法可以更容易地将其嵌入到GUMP中,请指出它!

回答

0

两个文件,其中一个包含所有的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'; 

形状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>