我面临以下问题。我有一个简单的文本区域,用户将在其中提交文本,随后将其写入服务器中的文本文件。这是有效的。
但是当我刷新页面时,它会再次将上次添加的文本添加到文本文件中,从而导致重复条目。
知道我必须做些什么来防止这种情况吗?下面是我用于文本区域部分的代码。
<html>
<body>
<form name="form" method="post">
<input type="text" name="text_box" size="50"/>
<input type="submit" id="search-submit" value="submit" />
</form>
</body>
</html>
<?php
if(isset($_POST['text_box'])) {
$a = $_POST['text_box'];
$myFile = "textfile.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
fwrite($fh, $a."'r'n");
fclose($fh);
}
?>
通过 POST 加载的页面将导致浏览器要求用户重新提交信息以查看页面,从而导致该页面执行的操作再次发生。如果页面是通过GET请求的,并且在查询字符串中有变量,则会发生同样的事情,但以静默方式发生(没有提示用户再次d它)。
解决此问题的最佳方法是使用 POST/REDIRECT/GET 模式。我在为 Authorize.Net 编写的关于处理付款的示例中使用了它。希望这能为你指明正确的方向。
更简单您可以在会话上存储一个简单的哈希值,然后每次都重新生成它。当用户重新加载页面时,php 不会被执行。
<?php
if(isset($_POST['text_box']) && $_SESSION['formFix'] == $_POST['fix']) {
$a = $_POST['text_box'];
$myFile = "textfile.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
fwrite($fh, $a."'r'n");
fclose($fh);
}
?>
<html>
<body>
<form name="form" method="post">
<input type="text" name="text_box" size="50"/>
<?php
$value = md5(rand(1,999999));
$_SESSION['formFix'] = $value;
?>
<input type="hidden" name="fix" value="<?= $value; ?>" />
<input type="submit" id="search-submit" value="submit" />
</form>
</body>
</html>
PS:块的顺序很重要,所以你需要反转它们。
正如约翰所说,您需要在表单提交后重定向用户。
fclose($fh);
// and
header("Location: success.php or where else");
exit;
注意:除非之前未调用ob_start
否则您的重定向将不起作用,因为您的页面包含 html 输出。
表单.php
<?php ob_start(); ?>
<html>
<body>
<? if (isset($_GET['success'])): ?>
Submit OK! <a href="form.php">New submit</a>
<? else: ?>
<form name="form" method="post" action="form.php">
<input type="text" name="text_box" size="50"/>
<input type="submit" id="search-submit" value="submit" />
</form>
<? endif; ?>
</body>
</html>
<?php
if(isset($_POST['text_box'])) {
$a = $_POST['text_box'];
$myFile = "textfile.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
fwrite($fh, $a."'r'n");
fclose($fh);
// send user
header("Location: form.php?success=1");
exit;
}
?>