PHP如何在刷新时清除内存

时间:2013-02-01 02:40:36

标签: php

我正面临以下问题。我有一个简单的textarea,用户将使用该文本提交文本,然后将其写入服务器中的文本文件。这很有效。

但是当我刷新页面时,它会将最后添加的文本添加到文本文件中,从而导致重复的条目。

知道我必须做些什么才能防止这种情况发生?下面是我用于textarea部分的代码。

<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);
    }
?>

提前致谢

3 个答案:

答案 0 :(得分:1)

通过POST加载的页面将导致浏览器要求用户重新提交信息以查看页面,从而导致该页面再次发生的操作。如果页面是通过GET请求的,并且在查询字符串中有变量,则会发生同样的事情,但是会无声地提示(不会再次提示用户)。

最好解决此问题的方法是使用POST/REDIRECT/GET pattern。我在一个关于processing payments that I wrote for Authorize.Net的例子中使用过它。希望这能指出你正确的方向。

答案 1 :(得分:0)

更简单 您只需在会话中存储一个简单的哈希值,并且每次都重新生成它。 当用户重新加载页面时,不会执行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:块的顺序很重要,因此你需要反转em。

答案 2 :(得分:0)

正如约翰所说,你需要在表单提交后重定向用户。

fclose($fh);
// and
header("Location: success.php or where else");
exit;

注意:除非之前没有调用ob_start,否则您的重定向将无法正常工作,因为您的页面包含html输出。

// form.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;
    }
?>
相关问题