我有一个页面“index.php”,其中有一个名为“add_users.php”的链接。在“add_users.php”中,我接受用户信息并返回到同一页面“index.php”,其中信息通过后操作传入并插入到数据库中。
当我刷新页面或点击后退按钮时,会出现一个重新发送框。我经历了许多解决方案,他们要求我创建第三页。我尝试这样做:在数据库中插入值后,我将页面重定向为 header('Location:http://thisisawebsite.com/thankyou.php http://thisisawebsite.com/thankyou.php,并在thankyou.php中我再次将页面重定向到index.php。但这导致收到警告“无法修改标头信息 - 标头已由 [...] 发送”
什么是更好的解决方案?
普里扬卡,
你走在正确的轨道上。您想要实现的实际上是网络开发中使用的一种众所周知的模式,称为POST/重定向/GET 模式 http://en.wikipedia.org/wiki/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
}
?>
那么,它的基本工作原理是这样的:
- 如果对脚本发出的请求不是 POST 请求(即表单尚未提交)并且没有
?message=success
附加到 url 然后简单地显示一个干净的表单。
- If the request made to the script IS a POST request, then process the form.
- If form processing succeeded, redirect to the same script again, and append
?message=success
- 如果对脚本的请求是带有
?message=success
附加到它只显示感谢信息,不显示表格。
- 如果表单处理失败,则让它“失败”并再次显示表单,但这次带有一些描述性错误消息,并且表单元素填充了用户已经填写的内容。
希望这与我给您的示例一起具有足够的意义。
现在,你被臭名昭著的原因Warning: headers already sent
消息已解释在这个答案中我给出了 https://stackoverflow.com/questions/2171139/what-means-by-top-of-the-page-in-php-file/2171305#2171305另一个问题是为什么某些 php 调用最好放在脚本的顶部(实际上,它不一定必须放在顶部,但必须在任何输出(甚至(意外的)空格)之前调用它)输出)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)