Prevent multiple POSTs when refresh in PHP



In this tutorial I will show you how to prevent multiple POSTs when refresh the page in PHP. For example a user is on contact us page and he fill the information and submit the form and than he refreshed the page for some reason. So this way duplicate entries can be inserted into database.

Simple Form Page Example
<?php 

// Database configs 
$host="localhost"; 
$dbuser="root"; 
$dbpass=""; 
$dbname = "simpledb";
 
// db connect 
$link = mysqli_connect($host, $dbuser, $dbpass, $dbname); 

if (mysqli_connect_errno()) 
  echo mysqli_connect_error(); 

if($_POST) { 
  $query = "INSERT INTO sample_table SET name = '".$_POST['name']."', post = '".$_POST['name']."' "; 
  mysqli_query($link, $query); 
  header("location: $_SERVER[PHP_SELF]"); 
  exit(); // Prevent Multiple Posts When Refresh the page 
} ?>
<!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Prevent multiple POSTs when refresh in PHP</title>
</head>
<body>
<form name="generalform" method="post">
	Name : <input type="text" name="name" />
	Post : <input type="text" name="post" />
    <input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
[/code

According to this example we can reload the page after saving POST information in PHP, so POST information will clear and no multiple entries will be stored in database. I hope this tutorial will help you to prevent multiple POSTs when refresh the page.