首页 文章

页面刷新提交我的表单

提问于
浏览
0
<?php
$rs = mysql_query("SELECT * FROM users WHERE id='$_SESSION[user_id]'");
while ($row= mysql_fetch_array($rs))
{
     $starter= $row['id'];
     $user_name= $row['user_name'];
}


$starterID=$starter;
$companyID=$_GET['id'];


$input = $_POST['message'];


date_default_timezone_set('Europe/Helsinki');
$timestamp = date('h:i', time());


$file = $companyID." and ".$starterID.".txt";


if (file_exists($file)) {
    $file = $companyID." and ".$starterID.".txt";
} else {
    $file = $starterID." and ".$companyID.".txt";
}


$current = file_get_contents($file);

$current.= "<b>$user_name</b> <br> $input $timestamp\n<br>";

if(isset($_POST['message'])){
file_put_contents($file, $current);
}

echo $current;
?>

<form action="" method="post">
<input type="text" name="message" autocomplete="off">
<input type="submit">
</form>

所以这是我在2个注册用户之间的非常简单的聊天 .

当ID为154的用户开始与ID 156进行对话时,将创建文件 154156.txt . 此文件是存储所有消息的位置 .

我的问题如下:假设用户154写了一条消息并通过按下提交按钮发送它,页面刷新并将消息存储到文件中并打印 . 在此之后,输入字段将清除,但如果用户刷新页面,则会再次存储和打印相同的消息 .

我该怎么做才能阻止页面刷新再次提交表单?

2 回答

  • 1

    您的页面仍保留 $_POST 值 . 所以,如果你刷新它 . 我再次转到 print 文件 .

    因此,添加 header 以重定向您的用户,如下所示:

    if(isset($_POST['message'])){
        file_put_contents($file, $current);
        header('Location:Your_File_name.php')
    }
    
  • 0

    我尝试了所有的建议,但不幸的是那些对我不起作用 .

    我做了一些更多的研究,发现这个案例和我的最佳解决方案如下:

    原始代码:

    if(isset($_POST['message']) && $_POST != null){
    file_put_contents($file, $current);
    }
    

    解:

    if(isset($_POST['message']) && $_POST != null){
    file_put_contents($file, $current);
    echo' <script type="text/javascript">
    location.reload();
    </script>';
    }
    

    感谢您的建议,他们让我更好地了解要搜索的内容:)

相关问题