Home >Backend Development >PHP Tutorial >How Can the Post-Redirect-Get (PRG) Pattern Prevent Form Resubmission in PHP?

How Can the Post-Redirect-Get (PRG) Pattern Prevent Form Resubmission in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-12-01 03:37:09200browse

How Can the Post-Redirect-Get (PRG) Pattern Prevent Form Resubmission in PHP?

Post-Redirect-Get (PRG) Pattern in PHP: Achieving Form Resubmission Protection

When designing web applications, preventing the resubmission of forms after page reloads or back button actions can enhance user experience and maintain data integrity. The Post-Redirect-Get (PRG) pattern is a widely recognized approach to address this issue, but finding straightforward PHP implementations can be challenging.

Here's a simplified example that demonstrates the PRG pattern in PHP:

<?php
if ($_POST) {
    // Validate input

    if (/* Input is valid */) {
        // Execute code (such as database updates) here.
        // Redirect to this page.
        header("Location: {$_SERVER['REQUEST_URI']}", true, 303);
        exit();
    }
}
?>
<html>
<!-- Your HTML page with a form -->
</html>

In this example, when the form is submitted via POST, the input is validated. If the input is valid, code such as database updates is executed. Subsequently, the script redirects the user to the same page using the Location header. The 303 See Other status code indicates that the request should be repeated via GET, effectively preventing form resubmission.

By using $_SERVER['REQUEST_URI'], this example avoids potential issues with PHP_SELF in CMS systems and frameworks. The exit() function is called to prevent the execution of the HTML code below the redirect.

This PRG implementation offers protection against form resubmission while minimizing code complexity. By employing this pattern, you can enhance the robustness and user experience of your web applications.

The above is the detailed content of How Can the Post-Redirect-Get (PRG) Pattern Prevent Form Resubmission in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn