简体   繁体   中英

Page refresh submits my form

<?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>

So this is my very simple chat between 2 registered users.

When user with ID 154 starts conversation with ID 156, file 154 and 156.txt is created. This file is where all the messages are stored.

My problem is following: when, let's say user 154 writes a message and sends it by pressing submit button the page refreshes and the message is stored to the file and also printed. After this the input field clears, but if the users refresh the page the same message is being stored and printed again.

What should I do to prevent page refresh submitting the form again?

Your page still hold the $_POST value. So, if you refresh it. iIts going to print the file again.

So, add header to redirect your user like this:

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

I tried all the suggestion but unfortunately those did not work for me.

I did some more research and found that the best solution for this case and me was the following:

original code:

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

solution:

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

Thanks for suggestions, they gave me an better idea what to search for :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM