2014-01-24 54 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,是的,我的错误 - 编辑它。谢谢 –