Refresh / refresh the page in the browser without re-submitting the form?

I have a form on a php page that submits to the same page. I noticed that if I reload / refresh the page, the form will be resubmitted. How is the code to avoid this in the easiest way?

+4
source share
3 answers

One possibility is to implement the post-redirect-get approach.

Simply put, a POST request will never be delivered to the browser. Instead, you perform all the necessary actions and store the necessary information in the session, and then you do the redirection with the code 303.

$page = 'show_result.php'; header('Location: '.$page, true, 303); exit; 

By doing this, the browser will display the show_result.php page (GET request) instead of the page requested by POST. This is also a page added to the story, so updating and using the back button will never execute another POST request. As a good side effect, you get rid of browser warnings about sending data, usually the user cannot decide what to do, anyway.

I think the biggest problem with this approach is that you need a session to store error messages, which means you have to rely on cookies. If you do not redirect the error display, the browser will display a warning about data transfer.

+2
source

This suggests a lot of things, but maybe this is what you are looking for:

 if ($_POST) { $success = false; /* * if all goes OK managing POST data make $success = true; * */ if ($success) { // this will redirects to your original // form page but using GET method // so re-submitting will be no possible header("location: {$_SERVER['PHP_SELF']}"); exit; } } 
+2
source

According to the HTTP standard, you must make a browser to execute a GET request after sending a POST. Here is an example sketch for processing a form:

 <? if ($_SERVER['REQUEST_METHOD']=='POST') { $err = array(); //performing all validations and raising corresponding errors if (empty($_POST['name']) $err[] = "Username field is required"; if (empty($_POST['text']) $err[] = "Comments field is required"; if (!$err) { //if no errors - saving data and redirect header("Location: ".$_SERVER['PHP_SELF']); exit; } else { // all field values should be escaped according to HTML standard foreach ($_POST as $key => $val) { $form[$key] = htmlspecialchars($val); } } else { $form['name'] = $form['comments'] = ''; } include 'form.tpl.php'; ?> 
0
source

Source: https://habr.com/ru/post/1379541/


All Articles