/    Sign up×
Community /Pin to ProfileBookmark

Stop form from sending twice?

What is the best way to stop a contact form from sending information twice if the user refreshes the page?

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@YelgnidrocMay 10.2008 — Try having a session variable $_SESSION['already_submitted']

Set it to TRUE after processing the form.

Only process the form if it's not TRUE
Copy linkTweet thisAlerts:
@apulmca2k4May 10.2008 — Redirect at another thanks page after processing data of form.
Copy linkTweet thisAlerts:
@GreyfishauthorMay 10.2008 — If don't like sending them to a page thats sole purpose is to say "Thankyou" I'd rather just keep it all on one page.

I can't figure out how to get this session variable thing to work, what is wrong with this?

[code=php]session_start();
$_SESSION['sent'] = "false";

if (isset($_POST["submit"])){
if ($_SESSION['sent'] == "false"){
$name = $_POST["name"];
$email = $_POST["email"];
$to = "[email protected]";
$subject = $_POST["subject"];
$message = $_POST["message"];
$body = "Full Name: $namen".
"E-mail Address: $emailn".
"Message: $message";
$header = "From: $email";
mail($to, $subject, $body, $header);
$_SESSION['sent'] = "true";
}
}[/code]
Copy linkTweet thisAlerts:
@YelgnidrocMay 10.2008 — You are always setting $_SESSION['sent'] = "false";

May be better to do something like:

[code=php]
if(!isset($_SESSION['sent']))
$_SESSION['sent'] = "false";


if (isset($_POST["submit"])){
if ($_SESSION['sent'] == "false"){
$name = $_POST["name"];
$email = $_POST["email"];
$to = "[email protected]";
$subject = $_POST["subject"];
$message = $_POST["message"];
$body = "Full Name: $namen".
"E-mail Address: $emailn".
"Message: $message";
$header = "From: $email";
mail($to, $subject, $body, $header);
$_SESSION['sent'] = "true";
}
}

[/code]
×

Success!

Help @Greyfish spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.4,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...