0

I have an email list page with a single input bar and a button that users can use to join my newsletter. The below php successfully adds a user's email to a table in an SQL database.

Once the user types in their email and clicks the button, the user is redirected to a confirmation page that lets them know that their email has been sent to the database.

My problem arises when I refresh the page after submitting an input. I've noticed that refreshing this confirmation page sends the same email item to the database, creating a duplicate (or if the page is refreshed 7 times, 7 duplicates).

In order to prevent this from happening, as well as preventing duplicate table items in general, what can be added to my below php code?

Sidenote: I'm just beginning to learn php, pdo and mysql, so if there is anything I'm missing in my code (further protection from sql injections, ) that you'd recommend, please let me know and/or attach sources where I can find further readings. Thank you. :)

<?php 
$dbHost = "";
$dbUser = "";
$dbPassword = "";
$dbName = "";

try {
  $dsn = "mysql:host=" . $dbHost . ";dbname=" . $dbName;
  $pdo = new PDO($dsn, $dbUser, $dbPassword);
} catch(PDOException $e) {
  echo "DB Connection Failed: " . $e->getMessage();
}

$status = "";
if($_SERVER['REQUEST_METHOD'] == 'GET') {
  $email = $_GET['email'];

  if(!filter_var($email, FILTER_VALIDATE_EMAIL))  {
      $status = "Please enter a valid email<br/>(no space at the end)";
    } else {

      $sql = "INSERT IGNORE INTO contactinfo (email) VALUES (:email)";

      $stmt = $pdo->prepare($sql);
      
      $stmt->execute(['email' => $email]);

      $status = "Success! Please click the confirmation link in the email I've sent you. It will expire in 12 hours.";
      $email = "";
    }
  }
?>
Strawberry
  • 33,750
  • 13
  • 40
  • 57

0 Answers0