首页 > 解决方案 > 防止刷新重新加载数据而不重定向到新页面

问题描述

我有一个将评论写入文件的单页评论 php 网页。但在刷新时,它会不断重新发布最后的评论。如何将其编码为仅在按下提交按钮时才写入文件。谢谢你。

<?php
    /*if($_POST)*/
    if(isset($_POST['submit_btn'])) {
        $name = $_POST['name'];
        $comment = $_POST['comment'];
        $handle = fopen("comments.php", "a");

        fwrite($handle, "<div><b><i>" . $name . "</b></i> update:<br>" . $comment . "<br></div><br>" );
        fclose($handle);
    }
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Rolling Log</title>
        <meta charset="uft-8">
    </head>
    <style>
        body {
          background-color: grey;
        }

        #top,#bottom {
          margin: 0 auto;
          width: 50%;
          padding: 5px;
        }

        div {
          border: 1px solid black;
          background-color: white;
        }
    </style>

    <body>
        <div id="top">
            <h1>Post a change mgmt comment</h1>

            <form action="" method="POST">
                Name: <br /> <input type="text" name="name"> <br />
                Comment: <br /> <textarea rows="5" cols="70" name="comment"></textarea> <br /><br />
                <input type="submit" name="submit_btn" value="Post comment">
            </form>
        </div>
        <br>

        <div id="bottom">
            <h1>Other CM Comments</h1>
            <?php include "comments.php"; ?>
        </div>
    </body>
</html>

标签: php

解决方案


使用标题刷新功能:header("Refresh:0");

这是因为当您向同一页面发送请求时,如果您不使用 header 函数强制它们,则 headers 不会更改(并且会保留当前在文件中添加数据的请求)。

 /*if($_POST)*/
    if(isset($_POST['submit_btn']))
    {
        $name = $_POST['name'];
        $comment = $_POST['comment'];
        $handle = fopen("comments.php", "a");
        fwrite($handle, "<div><b><i>" . $name . "</b></i> update:<br>" . $comment . "<br></div><br>" );
        fclose($handle);
        header("Refresh:0");
    }

推荐阅读