Reputation: 83
<?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?
Upvotes: 0
Views: 167
Reputation: 83
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 :)
Upvotes: 0
Reputation: 2509
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')
}
Upvotes: 1