繁体   English   中英

PHP表单写入文本文件-防止重新提交POST重定向

[英]php form writing to text file - prevent POST redirect re-submission

下面的代码是php形式,可写入txt文件并在同一页面上输出结果。

但是,当我刷新页面时,POST数据会自动再次添加-我想防止这种情况。 我知道我应该将用户重定向到另一页,但是如果我的结果在同一页上并且希望他们留在同一页上,该怎么办:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <title>Score Watch</title>
 </head>
<body>
 <p>
 <form id="form1" name="form1" method="post" action="">
 <label>Date: &nbsp;
<input name="date" class="datepicker" id="date" required type="text"
data-hint="" value="<?php echo date('d/m/Y'); ?>" />
 </label>
 <br>
 <label>Score:
 <input type="text" name="name" id="name" />
 </label>
  <label>
 <input type="submit" name="submit" id="submit" value="Submit" />
 </label>
 </form>
  </p>
 <?php
    $date = $_POST["date"];
    $name = $_POST["name"];
    $posts = file_get_contents("posts.txt");
    $posts = "$date $name<br>" . $posts;
    file_put_contents("posts.txt", $posts);
    echo $posts;
 ?>
</body>
 </html>

我已经看到header('Location')策略,但是由于我在同一页面上输出数据,所以无法使用它吗?

将此添加到您的页面顶部

<?php 
if(isset($_POST['name'],$_POST['date'])){
    // Text we want to add
    $posts = "{$_POST['date']} {$_POST['name']}<br>";

    // Add data to top of the file
    file_put_contents("posts.txt", $posts . file_get_contents('posts.txt') );

    // Redirect user to same page
    header('Location: ' . $_SERVER['REQUEST_URI']);
}
?>

稍微改变一下身体替换此:

<?php
    $date = $_POST["date"];
    $name = $_POST["name"];
    $posts = file_get_contents("posts.txt");
    $posts = "$date $name<br>" . $posts;
    file_put_contents("posts.txt", $posts);
    echo $posts;
?>

有了这个:

<?php
    // Print contents of posts.txt
    echo file_get_contents("posts.txt");
?>

如果您不想使用其他页面,则可以使用同一页面。 数据应通过GET或SESSION传输

为了防止循环重定向,您应该使重定向处于条件状态。

我会建议:

在页面顶部

<?php session_start(); ?>

然后

<?php
if (isset($_POST['date'])) {
    $date = $_POST["date"];
    $name = $_POST["name"];
    $posts = file_get_contents("posts.txt");
    $posts = "$date $name<br>" . $posts;
    file_put_contents("posts.txt", $posts);
    $_SESSION['posts'] = $posts;
    header("Location: samepage.php?success=1");
}
?>

<?php
if (isset($_GET['success'], $_SESSION['posts'])) {
    echo $_SESSION['posts']
}
?>

重定向也应该在HTML之前,以防止发送标头出现问题。

因为<p>是实际输出,所以只能在<p>内打印最后一个块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM