0

Ahoy!

Any help on this would be really appreciated! I have a contact form which is sending emails on a page refresh. I have tried a number of things and am not getting anywhere.. Heres what Ive got so far:

if(isset($_POST['email']) && $_POST['email'] != '') {

  if( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ){

    $userName = $_POST['name'];
    $userEmail = $_POST['email'];
    $messageSubject = $_POST['subject'];
    $message = $_POST['message'];

    $to = "email@gmail.com";
    $body = "";

    $body .= "From: " .$userName. "\r\n";
    $body .= "Email: " .$userEmail. "\r\n";
    $body .= "Message: " .$message. "\r\n";
    header('Location: http://www.website.net/contact-thank-you.html');
    exit();
    mail($to, $messageSubject, $body);

    
  }

  }

?>

Mark McKeon
  • 169
  • 2
  • 10

1 Answers1

0

The easiest way to prevent this is to redirect to a new URL after the email has been sent. Often websites will redirect to a "thank you" page.

You might be able to get away with redirecting to the same URL (and this won't send a second email because $_POST will be empty).

Another way would be to use the user session ($_SESSION) to keep track of whether the email was sent, and don't send an email again if you detect that $_SESSION indicates it was already sent. You could also use cookies for this same purpose. Last but not least you could store that information in a database and check the DB before sending an email so you don't send multiple emails.

kmoser
  • 8,780
  • 3
  • 24
  • 40
  • 1
    This is known as the [Post/Redirect/Get](https://en.wikipedia.org/wiki/Post/Redirect/Get) pattern, incidentally. – ceejayoz Oct 12 '20 at 01:44
  • Ok when I redirect to a new URL do I need to create this a html page? – Mark McKeon Oct 12 '20 at 01:51
  • @elsquidge You can just redirect to the same page since that page already exists, and that's effectively what's happening now (except that with this new method, reloads won't cause additional emails to be sent). For a better user experience, if this page doesn't have a confirmation message that the email was sent, you'll want to add that. Or, it might be easier to just redirect to another "thank you" page completely. – kmoser Oct 12 '20 at 02:00
  • You have to call `mail()` before you output headers and exit. – kmoser Oct 12 '20 at 05:21