Home >Backend Development >PHP Tutorial >How Can I Implement a Simple PHP Post-Redirect-Get (PRG) Pattern?

How Can I Implement a Simple PHP Post-Redirect-Get (PRG) Pattern?

DDD
DDDOriginal
2024-11-29 15:11:13258browse

How Can I Implement a Simple PHP Post-Redirect-Get (PRG) Pattern?

Simple PHP Post-Redirect-Get (PRG) Code Example

Implementing Post-Redirect-Get (PRG) in PHP can be straightforward. Here's a simplified example:

form.php

<form method="POST" action="validate.php">
   <!-- form elements -->
</form>

validate.php

<?php
if ($_POST) {
    // Validate input and execute code
    if (/* valid input */) {
        // Redirect to itself using REQUEST_URI
        header("Location: {$_SERVER['REQUEST_URI']}", true, 303);
        exit();
    }
}

submitted.php or invalid_input.php

<?php
echo $_SESSION['form_html'];

This script generates the form HTML stored in the session and displays it in case the user accesses the URL directly.

Benefits:

  • Protection against form resubmission and browser back button issues
  • Simple and straightforward implementation

Your approach to reinventing the wheel is not unreasonable. However, using the built-in HTTP status codes and header functions can help ensure reliable behavior and interoperability with other applications.

The above is the detailed content of How Can I Implement a Simple PHP Post-Redirect-Get (PRG) Pattern?. 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