Skip to content
PHP Logo

How can PHP code be prevented from executing multiple times when a page is refreshed in a web application?

When a page is refreshed in a web application, PHP code can execute multiple times, causing unintended consequences such as duplicate entries in a database or multiple emails being sent. To prevent this, we can use a technique called POST/Redirect/GET (PRG) pattern. This involves redirecting the user to a new page after processing a form submission, which prevents the form from being resubmitted if the user refreshes the page.

php
// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Process the form data
    
    // Redirect to a new page to prevent form resubmission
    header("Location: success.php");
    exit;
}