0

I used the mail function to do a contact form and it all works fine. However, I just noticed that after sending an email, every time a refresh the page, even though the fields are empty, an email keeps being sent.

My code looks like this:

<form role="form" method="POST">
    <br style="clear:both">
    <h3 style="margin-bottom: 25px; text-align: center;">Contact a Conveyancing Property Lawyer Now</h3>
    <div class="form-group">
    <input type="text" class="form-control" id="name" name="name" placeholder="Name" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
    </div>
    <div class="form-group">
    <input type="text" class="form-control" id="email" name="email" placeholder="Email" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
    </div>
    <div class="form-group">
    <input type="text" class="form-control" id="mobile" name="mobile" placeholder="Contact Number" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
    </div>
    <div class="form-group">
    <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
    </div>
    <div class="form-group">
        <select name="situation" id="situation">
            <option>Select Current Situation</option>
          <option class="placeholder" value="Unemployed">Unemployed</option>
          <option class="placeholder" value="Employed">Employed</option>
        </select>
    </div>
    <button type="submit" id="submit" name="submit" class="btn btn-primary">Submit</button>

    <?php
        if (isset($_POST["submit"])) {
            $name = $_POST['name'];
            $email = $_POST['email'];
            $mobile = $_POST['mobile'];
            $subject_line = $_POST['subject'];
            $situation = $_POST['situation'];
            $from = 'myemail@email.co.za'; 
            $to = 'myemail@email.co.za'; 
            $subject = 'SchoemanLaw lead ...';

            $body ="From: $name <br/> E-Mail: $email <br/> Mobile:  $mobile Subject: $subject_line <br/> Situation: $situation";

            //$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";

            // set content-type when sending HTML email
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

            // More headers optional/headers 
            $headers .= "From:$from";

             // Check if name has been entered
            if (!$_POST['name']) {
                $errName = 'Please enter your name';
            }

            // Check if email has been entered and is valid
            if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                $errEmail = 'Please enter a valid email address';
            }

             // Check if mobile has been entered
            if (!$_POST['mobile']) {
                $errMobile = 'Please enter your number';
            }

            // If there are no errors, send the email
            if (!$errName && !$errEmail && !$errMobile) {
                if (mail($to,$subject,$body,$headers)) {
                    $result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
                    echo $result;
                } else {
                    $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
                    echo $result;
                }
            }
        }   
    ?>
 </form>

How can I make the site forget all the details from the input fields once an email is sent?

I tried to follow this question here but I don't seem to be able to make it work on my site

Sidney Sousa
  • 3,378
  • 11
  • 48
  • 99
  • 1
    Separate the display code from the processing code; when the form is submitted it sends the data to a processing file which sends the email, when it's done it just does a `header()` 302 redirect to *"thank you"* page or whatever. Since the processing file just does a redirect nothing will be cached in the browser and that page *can't* be reloaded. – CD001 Jun 28 '17 at 08:16
  • Ideally I do not want a redirect to another page – Sidney Sousa Jun 28 '17 at 09:09
  • You can put the form and email processing into one file but you'll *need* the bit that *sends* the email to be different from the bit that displays the "thank you" message - if the bit that sends the email outputs *anything* to the browser the browser can cache it and it can be reloaded. – CD001 Jun 28 '17 at 15:12

7 Answers7

2

The easiest way is to add an forwarding in your code, like that:

EDIT: at @CD001 commentary

if (mail($to,$subject,$body,$headers)) {
  $result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
  echo $result;
  // header('Location: ?successfull-submit'); exit; // this one would fail because above is an output.
  echo '<meta http-equiv="refresh" content="0; url=?successfull-submit">'; // its not a good /nice alternative but it "works".
Richard
  • 618
  • 1
  • 9
  • 15
1

Redirect to ?sent=1 without sending any output. And check 'sent' to determine whether or not to display the success message. Try below (assuming your script is contact.php). Also make sure

contact.php

<?php
    $result = '';

    if (isset($_POST["submit"])) {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $mobile = $_POST['mobile'];
        $subject_line = $_POST['subject'];
        $situation = $_POST['situation'];
        $from = 'myemail@email.co.za'; 
        $to = 'myemail@email.co.za'; 
        $subject = 'SchoemanLaw lead ...';

        $body ="From: $name <br/> E-Mail: $email <br/> Mobile:  $mobile Subject: $subject_line <br/> Situation: $situation";

        //$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";

        // set content-type when sending HTML email
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

        // More headers optional/headers 
        $headers .= "From:$from";

         // Check if name has been entered
        if (!$_POST['name']) {
            $errName = 'Please enter your name';
        }

        // Check if email has been entered and is valid
        if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $errEmail = 'Please enter a valid email address';
        }

         // Check if mobile has been entered
        if (!$_POST['mobile']) {
            $errMobile = 'Please enter your number';
        }

        // If there are no errors, send the email
        if (!$errName && !$errEmail && !$errMobile) {
            if (mail($to,$subject,$body,$headers)) {
                //$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
                //echo $result;
                header('Location:' . 'contact.php?sent=1');
                exit;
            } else {
                $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
                //echo $result;
            }
        }
    }

    if(isset($_GET['sent'])) {
        $result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
    }   

    echo $result;
?>


<form role="form" method="POST">
    <br style="clear:both">
    <h3 style="margin-bottom: 25px; text-align: center;">Contact a Conveyancing Property Lawyer Now</h3>
    <div class="form-group">
    <input type="text" class="form-control" id="name" name="name" placeholder="Name" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
    </div>
    <div class="form-group">
    <input type="text" class="form-control" id="email" name="email" placeholder="Email" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
    </div>
    <div class="form-group">
    <input type="text" class="form-control" id="mobile" name="mobile" placeholder="Contact Number" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
    </div>
    <div class="form-group">
    <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
    </div>
    <div class="form-group">
        <select name="situation" id="situation">
            <option>Select Current Situation</option>
          <option class="placeholder" value="Unemployed">Unemployed</option>
          <option class="placeholder" value="Employed">Employed</option>
        </select>
    </div>
    <button type="submit" id="submit" name="submit" class="btn btn-primary">Submit</button>

 </form>
phpd
  • 551
  • 4
  • 10
0

You could use session variable and reset it after each request.

Or, prevent reloading same page using javascript.

Or, redirect to some other page upon completion (if possible)

Ravi
  • 30,829
  • 42
  • 119
  • 173
  • If you reset your $_POST with `$_POST=array(); ` it concerns only the code after this command. At a page reload the POST is still alive and have all values. – Richard Jun 28 '17 at 08:19
  • Correct. I will remove that part. – Ravi Jun 28 '17 at 08:20
  • Hope you dont mind updating the words with code snippet to make it easier for me. Just to emphasize, I dont really want to redirect to another page – Sidney Sousa Jun 28 '17 at 09:15
0

try like this,in your success message part..

<?php
        if (isset($_POST["submit"])) {
            $name = $_POST['name'];
            $email = $_POST['email'];
            $mobile = $_POST['mobile'];
            $subject_line = $_POST['subject'];
            $situation = $_POST['situation'];
            $from = 'myemail@email.co.za'; 
            $to = 'myemail@email.co.za'; 
            $subject = 'SchoemanLaw lead ...';

            $body ="From: $name <br/> E-Mail: $email <br/> Mobile:  $mobile Subject: $subject_line <br/> Situation: $situation";

            //$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";

            // set content-type when sending HTML email
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

            // More headers optional/headers 
            $headers .= "From:$from";

             // Check if name has been entered
            if (!$_POST['name']) {
                $errName = 'Please enter your name';
            }

            // Check if email has been entered and is valid
            if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                $errEmail = 'Please enter a valid email address';
            }

             // Check if mobile has been entered
            if (!$_POST['mobile']) {
                $errMobile = 'Please enter your number';
            }

            // If there are no errors, send the email
            if (!$errName && !$errEmail && !$errMobile) {
                if (mail($to,$subject,$body,$headers)) {
                     echo "<script>alert('Mail sent Successfully');</script>";
                     echo "<script>window.location = 'contact.php';</script>";
                } else {
                    echo "<script>alert('Mail not sent');</script>";
    echo "<script>window.location = 'contact.php';</script>";
                }
            }
        }   
    ?>

while redirect to another page you can restrict that duplication problem....

Mahesh
  • 93
  • 9
0

Just try redirecting to another page or another function that discards the old $_POST data.

Redgren Grumbholdt
  • 1,115
  • 1
  • 19
  • 36
0

You can try to add CSRF token to your page to prevent double submission. Refer to this link: How to prevent multiple form submission on multiple clicks in PHP

John Law
  • 15
  • 7
0

When the user refreshes the page, it is possible that the same parameters are getting posted again. As a result, if (isset($_POST["submit"])) This condition becomes true and mail will be sent every time user reloads.

One solution is to redirect to the same page or to a different page on success full completion.

ie,

if (mail($to,$subject,$body,$headers)) {
                $result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
                echo $result;
            } 

Instead of the above method, redirect user to the same page or different page and show a message there. If you want to show the same page you can redirect with a flag in the query string as ?show_success_msg= true.

Then do this.

if(isset($_GET['show_success_msg']) && $_GET['show_success_msg'] == 'true') {
  $result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
  echo $result;
}

Complete solution here:

<?php
    // Handle PHP code always on Top of the page (ie, Not after your HTML), You cant send headers if you have any content above it.

    if (isset($_POST["submit"])) {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $mobile = $_POST['mobile'];
        $subject_line = $_POST['subject'];
        $situation = $_POST['situation'];
        $from = 'myemail@email.co.za'; 
        $to = 'myemail@email.co.za'; 
        $subject = 'SchoemanLaw lead ...';

        $body ="From: $name <br/> E-Mail: $email <br/> Mobile:  $mobile Subject: $subject_line <br/> Situation: $situation";

        //$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";

        // set content-type when sending HTML email
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

        // More headers optional/headers 
        $headers .= "From:$from";

         // Check if name has been entered
        if (!$_POST['name']) {
            $errName = 'Please enter your name';
        }

        // Check if email has been entered and is valid
        if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $errEmail = 'Please enter a valid email address';
        }

         // Check if mobile has been entered
        if (!$_POST['mobile']) {
            $errMobile = 'Please enter your number';
        }

        // If there are no errors, send the email
        if (!$errName && !$errEmail && !$errMobile) {
            if (mail($to,$subject,$body,$headers)) {
                $result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
                echo $result;
            } else {
                header("Location: your_page.php?show_success_msg=true")
            }
        }
    }   
?>
<form role="form" method="POST">
<?php if(isset($_GET['show_success_msg']) && $_GET['show_success_msg'] == 
'true') {
$result='<div class="alert alert-success">Thank You ! We will be in touch 
soon</div>';
echo $result;
} ?>

<br style="clear:both">
<h3 style="margin-bottom: 25px; text-align: center;">Contact a Conveyancing Property Lawyer Now</h3>
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="email" name="email" placeholder="Email" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Contact Number" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
    <select name="situation" id="situation">
        <option>Select Current Situation</option>
      <option class="placeholder" value="Unemployed">Unemployed</option>
      <option class="placeholder" value="Employed">Employed</option>
    </select>
</div>
<button type="submit" id="submit" name="submit" class="btn btn-primary">Submit</button>

Codeformer
  • 2,060
  • 9
  • 28
  • 46
  • I don't quite follow the use of show_success_msg. Hope you don't mind updating your answer with a full php code based on mine. Ideally I do not want a redirect to another page. Appreciate the support – Sidney Sousa Jun 28 '17 at 09:12
  • Done, Hope it helps. – Codeformer Jun 28 '17 at 10:00
  • The behavior is still the same. Actually, after submitting the form for the first time and I refresh the page, I see an alert that says that if I refresh the page, data will be repeatedly sent. – Sidney Sousa Jun 28 '17 at 10:55
  • Then it was not redirected properly for some reason , do you see the new URL with the query string flag ? – Codeformer Jun 28 '17 at 11:12
  • You maybe want to check the logic around `if (mail($to,$subject,$body,$headers)) { $result='
    Thank You ! We will be in touch soon
    '; echo $result; } else { header("Location: your_page.php?show_success_msg=true") }`
    – CD001 Jun 28 '17 at 15:18