Inline Code Example HereHi,
the php code which

<html>
<body>
<?php 
$fs =fopen("comments.txt",'a');
$jina = $_POST["fname"];
$message = $_POST["message"];
$time = date("d/m/y : H:i:s", time()) ;
//limit leght characters
//$message = wordwrap($message, 5);
fwrite($fs,$message);
fwrite($fs, "\n<i>Posted By </i> ".$jina." <i>on </i>");
fwrite($fs, $time);
fwrite($fs, "<hr />");
$fs= fopen("comments.txt", 'r');
while (!feof($fs))
{
echo fgets($fs)."<br />";
}
fclose($fs);
/*<html>
<body onLoad="location.href='#chini'">
//<a name="chini"> </a>
</body>
</html>
*/
?>
</body>
</html>

writes the contents to the txt file, but the problem is when I click refresh button it writes the data as many times as I refresh the page. how can I avoid it.
Regards

Dani AI

Generated

The problem is the classic POST resubmission: the browser replays the same POST when the page is refreshed, so the same comment gets appended repeatedly. The simplest robust fix is the Post/Redirect/Get (PRG) pattern plus a single-use token or short server-side duplicate check. pointed toward redirect/session flags; the approach below expands that into a safe, practical workflow.

Example (processor + single-use token + safe append):

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (empty($_POST['token']) || !isset($_SESSION['token']) || $_POST['token'] !== $_SESSION['token']) {
        header('Location: /form.php'); exit;
    }
    unset($_SESSION['token']); // consume token

    $name = trim($_POST['fname'] ?? '');
    $msg  = trim($_POST['message'] ?? '');
    if ($msg === '') { header('Location: /form.php'); exit; }

    $hash = sha1($name . '|' . $msg);
    if (isset($_SESSION['last_hash']) && $_SESSION['last_hash'] === $hash) {
        header('Location: /form.php'); exit;
    }
    $_SESSION['last_hash'] = $hash;

    $entry = htmlspecialchars($msg, ENT_QUOTES) . " - Posted by " . htmlspecialchars($name, ENT_QUOTES) . " at " . date('Y-m-d H:i:s') . "\n<hr/>\n";
    file_put_contents(__DIR__ . '/comments.txt', $entry, FILE_APPEND | LOCK_EX);

    header('Location: /form.php'); exit; // PRG: refresh now repeats GET, not POST
}
?>

Notes and cautions

  • Generate the hidden token on the form page (session_start(); $_SESSION['token']=bin2hex(random_bytes(16));) and include it as a hidden input.
  • header() must run before any output; follow it with exit. Consider sending a 303 status for strictness.
  • Use LOCK_EX or flock() to avoid concurrent write corruption. Check file permissions.
  • Keep a short server-side duplicate check (hash + timestamp in session) to catch retries or double clicks.
  • Sanitize output (htmlspecialchars) when showing comments. For higher traffic or concurrency, migrate to a database rather than a flat file.

This builds on 's redirect/session idea and gives a concrete PRG + token pattern that prevents duplicate writes on refresh while keeping the write operation atomic and safe.

Member Avatar for Member #120589

A script like this could be a standalone which then redirects back to the original page.

You could use a flag variable to prevent the code runnign again, e.g. with sessions or use a cookie - but cookies can be turned off.

form page -> filecreator -> form page

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.