2014-01-24 52 views
0

下面的代碼是一個php表單,寫入一個txt文件並在同一頁輸出結果。php表單寫入文本文件 - 防止POST重定向重新提交

但是,當我刷新頁面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')戰術,但我不能使用它,因爲我在同一頁上輸出數據?

+2

保存數據會話,或通過獲取方法傳遞它 –

回答

3

此項添加到頂部,你頁面的

<?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"); 
?> 
+0

+1也許輸出文件內容是整個想法:) –

+0

完美,謝謝。 – user3232284

+0

最後,我將如何修改我的代碼,以便最新的數據提交出現在輸出的頂部?不是一個接一個。我需要扭轉訂單數據輸出,最新的提交在頂部。 – user3232284

1

如果您不想使用其他頁面,則可以使用同一頁面。數據應通過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>的內部,因爲它是實際的輸出。

+1

@jeroen ouch,是的,我的錯誤 - 編輯它。謝謝 –