我有一个向SQL表提交文本的简单表单。问题在于,在用户提交文本之后,他们可以刷新页面并再次提交数据,而无需再次填写表单。我可以在文本提交后将用户重定向到另一个页面,但我希望用户停留在同一页面上。
我记得我读过一些关于给每个用户一个唯一的会话id,并将其与另一个值进行比较,这解决了我所遇到的问题,但我忘记了它在哪里。
我有一个向SQL表提交文本的简单表单。问题在于,在用户提交文本之后,他们可以刷新页面并再次提交数据,而无需再次填写表单。我可以在文本提交后将用户重定向到另一个页面,但我希望用户停留在同一页面上。
我记得我读过一些关于给每个用户一个唯一的会话id,并将其与另一个值进行比较,这解决了我所遇到的问题,但我忘记了它在哪里。
处理表单时,重定向到另一个页面:
... process complete....
header('Location: thankyou.php');
您也可以重定向到同一页面。
如果您正在做一些类似评论的事情,并且希望用户停留在相同的页面上,您可以使用Ajax来处理表单提交
使用Post/Redirect/Get模式。http://en.wikipedia.org/wiki/Post/Redirect/Get
对于我的网站,我将在cookie或会话中存储消息,在发布后重定向,读取cookie/会话,然后清除该会话或cookie变量的值。
为什么不直接使用$_POST['submit']变量作为逻辑语句来保存表单中的任何内容呢?你总是可以重定向到相同的页面(以防它们刷新,当它们在浏览器中点击返回时,submit post变量将不再被设置。只要确保你的提交按钮有一个名称和id提交。
使用头和重定向页面。 标题(“位置:your_page.php”);您可以重定向到相同的页面或不同的页面。 将$_POST插入数据库后取消设置。 设置($ _POST);
你真的应该使用Post Redirect Get模式来处理这个问题,但如果你在某种程度上陷入了PRG不可行的境地(例如,表单本身在一个include中,防止重定向),你可以散列一些请求参数,根据内容生成一个字符串,然后检查你是否已经发送了它。
//create digest of the form submission:
$messageIdent = md5($_POST['name'] . $_POST['email'] . $_POST['phone'] . $_POST['comment']);
//and check it against the stored value:
$sessionMessageIdent = isset($_SESSION['messageIdent'])?$_SESSION['messageIdent']:'';
if($messageIdent!=$sessionMessageIdent){//if its different:
//save the session var:
$_SESSION['messageIdent'] = $messageIdent;
//and...
do_your_thang();
} else {
//you've sent this already!
}
一个非常可靠的方法是在post中实现一个唯一的ID,并将其缓存到
<input type='hidden' name='post_id' value='".createPassword(64)."'>
然后在你的代码中这样做:
if( ($_SESSION['post_id'] != $_POST['post_id']) )
{
$_SESSION['post_id'] = $_POST['post_id'];
//do post stuff
} else {
//normal display
}
function createPassword($length)
{
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= ($length - 1)) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
Moob帖子的精炼版。创建POST的散列,将其保存为会话cookie,并比较每个会话的散列。
// Optionally Disable browser caching on "Back"
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Expires: Sun, 1 Jan 2000 12:00:00 GMT' );
header( 'Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT' );
$post_hash = md5( json_encode( $_POST ) );
if( session_start() )
{
$post_resubmitted = isset( $_SESSION[ 'post_hash' ] ) && $_SESSION[ 'post_hash' ] == $post_hash;
$_SESSION[ 'post_hash' ] = $post_hash;
session_write_close();
}
else
{
$post_resubmitted = false;
}
if ( $post_resubmitted ) {
// POST was resubmitted
}
else
{
// POST was submitted normally
}
插入到数据库后,调用unset()方法清除数据。
设置($ _POST);
为防止刷新数据插入,请在记录插入后将页面重定向到同一页或不同页。
头(地点:。$ _SERVER [' PHP_SELF ']);
基本上,你需要重定向出该页面,但它仍然可以使一个问题,而你的互联网缓慢(重定向头从服务器端)
基本场景示例:
点击提交按钮两次
解决方法
客户端 一旦客户端点击它,禁用提交按钮 如果你使用Jquery: Jquery.one PRG模式 服务器端 使用基于差分的哈希时间戳/发送请求时的时间戳。 Userequest令牌。当主进程加载完成时,分配一个临时请求标记,如果重复则忽略该标记。
使用Keverw answer的Post/Redirect/Get模式是个好主意。然而,你不能留在你的页面上(我认为这是你所要求的?)此外,它有时可能会失败:
如果web用户在首次提交完成之前刷新 由于服务器延迟,导致重复的HTTP POST请求在 某些用户代理。
另一个选择是存储在会话中,如果文本应该像这样写入SQL数据库:
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
$_SESSION['writeSQL'] = true;
}
else
{
if(isset($_SESSION['writeSQL']) && $_SESSION['writeSQL'])
{
$_SESSION['writeSQL'] = false;
/* save $_POST values into SQL */
}
}
您可以通过会话变量防止表单重新提交。
首先,你必须在文本框中设置rand(),并在表单页面上设置$_SESSION['rand']:
<form action="" method="post">
<?php
$rand=rand();
$_SESSION['rand']=$rand;
?>
<input type="hidden" value="<?php echo $rand; ?>" name="randcheck" />
Your Form's Other Field
<input type="submit" name="submitbtn" value="submit" />
</form>
在此之后,检查$_SESSION['rand']与文本框$_POST['randcheck']值 是这样的:
if(isset($_POST['submitbtn']) && $_POST['randcheck']==$_SESSION['rand'])
{
// Your code here
}
确保在使用session_start()的每个文件上都启动会话。
我还想指出,您可以使用javascript方法window.history.replaceState来防止在刷新和返回按钮时重新提交。
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
这里的概念证明:https://dtbaker.net/files/prevent-post-resubmit.php(链接不再工作)
我仍然推荐Post/Redirect/Get方法,但这是一个新颖的JS解决方案。
如何防止php表单重新提交没有重定向。如果你正在使用$_SESSION(在session_start之后)和$_POST表单,你可以这样做:
if ( !empty($_SESSION['act']) && !empty($_POST['act']) && $_POST['act'] == $_SESSION['act'] ) {
// do your stuff, save data into database, etc
}
在你的html表单中放这个:
<input type="hidden" id="act" name="act" value="<?php echo ( empty($_POST['act']) || $_POST['act']==2 )? 1 : 2; ?>">
<?php
if ( $_POST['act'] == $_SESSION['act'] ){
if ( empty( $_SESSION['act'] ) || $_SESSION['act'] == 2 ){
$_SESSION['act'] = 1;
} else {
$_SESSION['act'] = 2;
}
}
?>
因此,每当表单提交时,都会生成一个新的行为,存储在会话中并与后行为进行比较。
Ps:如果你正在使用一个Get表单,你可以很容易地用Get更改所有POST,它也可以工作。
我找到了下一个变通办法。您可以通过操作历史对象在处理POST请求后转义重定向。
你有一个HTML表单
<form method=POST action='/process.php'>
<input type=submit value=OK>
</form>
当你在你的服务器上处理这个表单时,你不是重定向用户到/the/result/页面,而是像这样设置Location头:
$cat process.php
<?php
process POST data here
...
header('Location: /the/result/page');
exit();
?>
处理post数据后,呈现小的<脚本>和result/ the/result/page
<?php
process POST data here
render the <script> // see below
render `/the/result/page` // OK
?>
你应该渲染的<脚本>:
<script>
window.onload = function() {
history.replaceState("", "", "/the/result/page");
}
</script>
结果是:
如你所见,表单数据被post到process.php脚本。 这个脚本处理post数据并立即渲染/the/result/page:
没有重定向 当你刷新页面时没有rePOST数据(F5) 当你通过浏览器历史导航到上一页/下一页时,没有rePOST
UPD
作为另一个解决方案,我要求Mozilla FireFox团队允许用户设置NextPage头,它将像Location头一样工作,使post/redirect/get模式过时。
简而言之。当服务器处理表单POST数据成功时:
设置NextPage头而不是位置 呈现POST表单数据处理的结果,就像在POST /redirect/ GET模式中呈现GET请求一样
浏览器依次看到NextPage头:
调整窗口。位置与NextPage值 当用户刷新页面时,浏览器将协商GET请求NextPage而不是rePOST表单数据
我认为这将是极好的,如果实施,不是吗?=)
正如其他人所说,不可能不使用post/redirect/get。但与此同时,在服务器端做你想做的事情也很容易。
在POST页面中,只需验证用户输入,但不对其进行操作,而是将其复制到SESSION数组中。然后再次重定向到主提交页面。您的主提交页面首先检查您正在使用的SESSION数组是否存在,如果存在,则将其复制到本地数组中并取消设置。从那里你可以采取行动。
这样你只需要做一次主要的工作,就能完成你想做的事情。
我寻找解决方案,以防止在一个巨大的项目之后再次提交。 代码高度工作与$_GET和$_POST和我不能改变表单元素的行为没有不可预见的错误的风险。 这是我的代码:
<!-- language: lang-php -->
<?php
// Very top of your code:
// Start session:
session_start();
// If Post Form Data send and no File Upload
if ( empty( $_FILES ) && ! empty( $_POST ) ) {
// Store Post Form Data in Session Variable
$_SESSION["POST"] = $_POST;
// Reload Page if there were no outputs
if ( ! headers_sent() ) {
// Build URL to reload with GET Parameters
// Change https to http if your site has no ssl
$location = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// Reload Page
header( "location: " . $location, true, 303 );
// Stop any further progress
die();
}
}
// Rebuilt POST Form Data from Session Variable
if ( isset( $_SESSION["POST"] ) ) {
$_POST = $_SESSION["POST"];
// Tell PHP that POST is sent
$_SERVER['REQUEST_METHOD'] = 'POST';
}
// Your code:
?><html>
<head>
<title>GET/POST Resubmit</title>
</head>
<body>
<h1>Forms:</h1>
<h2>GET Form:</h2>
<form action="index.php" method="get">
<input type="text" id="text_get" value="test text get" name="text_get"/>
<input type="submit" value="submit">
</form>
<h2>POST Form:</h2>
<form action="index.php" method="post">
<input type="text" id="text_post" value="test text post" name="text_post"/>
<input type="submit" value="submit">
</form>
<h2>POST Form with GET action:</h2>
<form action="index.php?text_get2=getwithpost" method="post">
<input type="text" id="text_post2" value="test text get post" name="text_post2"/>
<input type="submit" value="submit">
</form>
<h2>File Upload Form:</h2>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file">
<input type="submit" value="submit">
</form>
<h1>Results:</h1>
<h2>GET Form Result:</h2>
<p>text_get: <?php echo $_GET["text_get"]; ?></p>
<h2>POST Form Result:</h2>
<p>text_post: <?php echo $_POST["text_post"]; ?></p>
<h2>POST Form with GET Result:</h2>
<p>text_get2: <?php echo $_GET["text_get2"]; ?></p>
<p>text_post2: <?php echo $_POST["text_post2"]; ?></p>
<h2>File Upload:</h2>
<p>file:
<pre><?php if ( ! empty( $_FILES ) ) {
echo print_r( $_FILES, true );
} ?></pre>
</p>
<p></p>
</body>
</html><?php
// Very Bottom of your code:
// Kill Post Form Data Session Variable, so User can reload the Page without sending post data twice
unset( $_SESSION["POST"] );
它只能避免$_POST的重新提交,而不是$_GET的重新提交。但这是我需要的行为。 重新提交的问题不工作的文件上传!
我使用这个javascript行来阻止弹出窗口要求表单重新提交刷新一旦表单提交。
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
只需将这一行放在文件的页脚,就能看到神奇的效果
if (($_SERVER['REQUEST_METHOD'] == 'POST') and (isset($_SESSION['uniq']))){
if($everything_fine){
unset($_SESSION['uniq']);
}
}
else{
$_SESSION['uniq'] = uniqid();
}
$everything_fine是表单验证的布尔结果。如果表单没有验证,那么通常会再次显示,并提示需要更正的内容,以便用户可以再次发送。因此,如果需要更正的形式,也会再次创建$_SESSION['uniq']
对我有用的是:
if ( !refreshed()) {
//Your Submit Here
if (isset( $_GET['refresh'])) {
setcookie("refresh",$_GET['refresh'], time() + (86400 * 5), "/");
}
}
}
function refreshed()
{
if (isset($_GET['refresh'])) {
$token = $_GET['refresh'];
if (isset($_COOKIE['refresh'])) {
if ($_COOKIE['refresh'] != $token) {
return false;
} else {
return true;
}
} else {
return false;
}
} else {
return false;
}
}
function createToken($length) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
?>
在你的表格中
<form action="?refresh=<?php echo createToken(3)?>">
</form>
这个form.php示例展示了如何正确地使用PRG(当表单有效或无效时)。
它只在表单有效且执行操作时重定向到相同的页面。 重定向可以防止表单在页面刷新时被重新提交。 当表单有效时,它使用session来避免丢失想要显示的成功消息。 有两个测试按钮:“有效提交”,“无效提交”。两者都试一下,然后刷新页面。
<?php
session_start();
function doSelfRedirect()
{
header('Location:'.$_SERVER['PHP_SELF']);
exit;
}
function setFlashMessage($msg)
{
$_SESSION['message'] = $msg;
}
function getFlashMessage()
{
if (!empty($_SESSION['message'])) {
$msg = $_SESSION['message'];
unset($_SESSION['message']);
} else {
$msg = null;
}
return $msg;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Validation primitive example.
if (empty($_POST['valid'])) {
$formIsValid = false;
setFlashMessage('Invalid form submit');
} else {
$formIsValid = true;
}
if ($formIsValid) {
// Perform any actions here.
// ...
// Cool!
setFlashMessage('Form is valid. Action performed.');
// Prevent form resubmission.
doSelfRedirect();
}
}
?>
<h1>Hello form</h1>
<?php if ($msg = getFlashMessage()): ?>
<div><?= $msg ?></div>
<?php endif; ?>
<form method="post">
<input type="text" name="foo" value="bar"><br><br>
<button type="submit" name="invalid" value="0">Invalid submit</button>
<button type="submit" name="valid" value="1">Valid submit</button>
</form>
$_POST['submit']变量在页面初始加载时不存在,并且只有在以下条件为真时才可以运行curl。
if($_POST['submit'] == "submit"){
// This is where you run the Curl code and display the output
$curl = curl_init();
//clear $post variables after posting
$_POST = array();
}