簡體   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