Hello guys, i got a small problem here.

I can write and press "send" to submit a private message to a memeber, right... but if i refresh the page, the message gets sent again..

Anyone know a small php script i could put on top of the page to avoid script re-run?

Dani AI

Generated

The browser is resubmitting the POST on refresh, so the form handler runs again. and have pointed to the common PRG/redirect approach; that works. To make the fix more robust (and avoid relying only on redirects or JS), add a server-side one-time token and a simple duplicate-check before inserting the message.

A compact token flow (session nonce):

/* on form page */
session_start();
if (empty($_SESSION['msg_token'])) {
    $_SESSION['msg_token'] = bin2hex(random_bytes(32)); /* PHP 7+ */
}
/* include hidden input name="msg_token" with value $_SESSION['msg_token'] */

Validate and consume the token in the handler:

/* in the POST handler */
session_start();
$token = $_POST['msg_token'] ?? '';
if (!isset($_SESSION['msg_token']) || !hash_equals($_SESSION['msg_token'], $token)) {
    /* ignore duplicate/invalid submission */
    exit;
}
unset($_SESSION['msg_token']); /* make token single‑use */
/* proceed to insert message */

Add a server-side dedupe check as a safety net (detect recent identical submissions):

$hash = hash('sha256', $from.'|'.$to.'|'.$message);
$stmt = $pdo->prepare(
  'SELECT id FROM messages WHERE message_hash = ? AND created_at > (NOW() - INTERVAL 2 MINUTE)'
);
$stmt->execute([$hash]);
if ($stmt->fetch()) {
  /* treat as duplicate */
} else {
  $pdo->prepare(
    'INSERT INTO messages (from_id,to_id,body,message_hash) VALUES (?,?,?,?)'
  )->execute([$from,$to,$message,$hash]);
}

Client-side disabling of the submit button or using AJAX can reduce accidental double-clicks, but must not replace server checks. For background reading, see the Post/Redirect/Get pattern and CSRF/token guidance: Post/Redirect/Get, OWASP CSRF Prevention Cheat Sheet.

Notes: session_start() is required for tokens. Use a cryptographically secure generator (random_bytes or openssl_random_pseudo_bytes). Keep server-side dedupe windows short (1–5 minutes) to avoid blocking legitimate repeats.

Recommended Answers

All 2 Replies

Member Avatar for Member #120589

Don't send the form to itself (same page). Send it to a form handler file and then redirect back to the form page. Refresh will no longer reload said form.

Because you haven't provided header after your logic.
Lets your page name is 'page.php'.

<?
	if(condition)
	{
		// your 
		// message
		// sending
		// code
		header("location:page.php");
		exit;
	}
?>
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.