Home  >  Article  >  Backend Development  >  How to Prevent Form Resubmission in PHP Pages?

How to Prevent Form Resubmission in PHP Pages?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-03 11:11:29770browse

How to Prevent Form Resubmission in PHP Pages?

Avoiding Form Resubmission in PHP Pages

When refreshing PHP pages that contain an insert function, you may encounter the issue of form resubmission, which can lead to duplicate data being inserted. To prevent this, consider employing the Post-Redirect-Get (PRG) pattern.

PRG Pattern

The PRG pattern involves:

  1. Accepting a POST request: Receive the submitted form data.
  2. Processing the data: Validate, insert, or perform any necessary actions.
  3. Issuing a redirect response: Redirect the user to a new URL.
  4. Accepting a GET request: The user clicks the refreshed link and makes a new request.
  5. Issuing a 200 response: Display the page with any necessary data.

Example

For instance, suppose you're creating a page where users can add notes. Instead of using an insert function in the same page, you can implement the PRG pattern as follows:

  • Page 1 (add_note.php): Display the form.
  • Page 2 (process_note.php): Accept the POST request and process the note submission.
  • Page 3 (view_notes.php): Accept the GET request and display the updated notes.

Handling Form Data Display

If you need to display data from the submitted form after processing, you can include a unique identifier in the query string of the redirect URL. For example, your redirect response from process_note.php might be:

<code class="php">header("Location: view_notes.php?note_id=$new_note_id");</code>

In view_notes.php, you can then use the note_id from the query string to retrieve and display the newly inserted note.

The above is the detailed content of How to Prevent Form Resubmission in PHP Pages?. 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