POST/Redirect/GET错误处理


POST/Redirect/GET with Error handling

写这篇文章的原因是我想避免大多数浏览器在刷新表单时发出的"表单重新提交错误"。

看下面的例子:

用户在一个名为signpetition.php的页面上,并显示了一个基本的HTML表单:

<div id="sign-errors" style="display: none;">
</div>
<form action="" method="post">
    <input type="submit" name="submit_button" value="sign petition" />
</form>

因此,用户单击submit按钮,现在将读取并验证POST数据。

signpetition.php

<?php
    if(isset($_POST['submit_button']))
    {
        // Do some validation
        if($errors == true)
        {
          // What to do here? I want to go back to the last page, but keep the errors. Should I store them in a session variable and then unset them after their use? I feel as though there must be a better solution to this.
            $_SESSION['error'] = "the error";
            header('Location: '. $_SERVER['REQUEST_URI'] , true, 303);
        exit;
        }
        else
        {
            $_SESSION['success'] = "your petition was successfully signed!";
            header('Location: '. $_SERVER['REQUEST_URI'] , true, 303);
        exit;
        }
    }
        ?>

总结一下:

我想避免表单重新提交的问题,这就是为什么我使用在我的代码头重定向

如果用户被重定向,那么就不应该重新提交表单。

将它们重定向到submitted.php,并使用以下命令:

if(isset($_SESSION['error'])){ echo'the error';}
else if(isset($_SESSION['success'])){ echo'your petition was successfully signed!');}
else{ echo 'unknown error.'; }

我知道这是旧的,但我想补充的是,关于将消息存储在SESSION对象中以供单一使用,您的原始解决方案没有任何问题。这是一种常见的做法,称为"Flash消息",它是存储在会话中的消息,当读取一次时将被删除。该技术因Rails而流行起来。下面是一个PHP摘要:

http://www.phpdevtips.com/2013/05/simple-session-based-flash-messages/