
Preventing form resubmission and ensuring a smooth user experience is essential when handling data in PHP. The Post/Redirect/Get (PRG) pattern is a reliable approach to achieve this.
✅ PHP Form Handling with Page Refresh
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Process form data (e.g., store in database or send an email)
$name = $_POST['name'] ?? '';
// Perform your logic here (e.g., save to database)
// Redirect to avoid form resubmission
header("Location: " . $_SERVER['PHP_SELF']);
exit(); // Stops further script execution
}
?>
✅ HTML Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Refresh Example</title>
</head>
<body>
<h2>Submit Form and Refresh</h2>
<form method="POST" action="">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
Explanation
-
Check the request method: Handles the form submission only when the
POST
method is used. -
Process the data: Save it to the database or handle it as needed.
-
Redirect using
header()
: Redirect to the same page using$_SERVER['PHP_SELF']
. -
Use
exit()
: Prevents further script execution after the redirect.
✅ Benefits
-
Prevents duplicate form submission when the page is refreshed.
-
Clears the
POST
data from the browser's history.
By following this approach, you can enhance user experience and avoid accidental resubmissions.