我有一个页面"index.php",其中我有一个名为"add_users.php"的链接.在"add_users.php"中,我接受用户信息并返回到同一页面"index.php",其中信息通过后期操作进入并插入到数据库中.
当我刷新页面或点击后退按钮时,会出现重新发送框.我经历了许多解决方案,他们要求我创建第三页.我尝试如下操作:在数据库中插入值后,我将页面重定向为标题('Location:http://thisisawebsite.com/thankyou.php,并在thankyou.php中我再次将页面重定向到index.php.但是这导致收到警告"无法修改标题信息 - 已经由[....]发送的标题"
什么是更好的解决方案?
Dec*_*ler 19
普里,
你走在正确的轨道上.您要实现的实际上是Web开发中使用的一种众所周知的模式,称为POST/Redirect/GET模式.(模式现在是一个流行词,所以也许范式是一个更好的词).
这种模式/范例的一个常见实现是只有一个入口点.
通过这样做,add_user.php现在看起来像这样(它仍然不是最优雅的,但希望它会让你知道如何实现它):
<?php
// is this a post request?
if( !empty( $_POST ) )
{
/*
process the form submission
and on success (a boolean value which you would put in $success), do a redirect
*/
if( $success )
{
header( 'HTTP/1.1 303 See Other' );
header( 'Location: http://www.example.com/add_user.php?message=success' );
exit();
}
/*
if not successful, simply fall through here
*/
}
// has the form submission succeeded? then only show the thank you message
if( isset( $_GET[ 'message' ] ) && $_GET[ 'message' ] == 'success' )
{
?>
<h2>Thank you</h2>
<p>
You details have been submitted succesfully.
</p>
<?php
}
// else show the form, either a clean one or with possible error messages
else
{
?>
<!-- here you would put the html of the form, either a clean one or with possible error messages -->
<?php
}
?>
Run Code Online (Sandbox Code Playgroud)
那么,它基本上是如何工作的:
?message=success附加到URL,则只需显示一个干净的表单.?message=success
?message=success附加到它的请求,则只显示感谢信息,不要显示表单.希望这一点,以及我给你的例子,都足够了.
现在,你得到臭名昭着的Warning: headers already sent消息的原因在这个答案中解释了我给另一个问题,为什么某些php调用更好地放在脚本的顶部(实际上,它不一定必须在顶部,但是必须在输出任何输出(偶数(偶然)空白)之前调用它.