简体   繁体   中英

PHP refresh, how can I stop the previous function being called again on page refresh?

I have a function that imports a files contents into mySQL and returns the results. If i refresh the page and click "yes" it will do it again doubling the output with the same content.

How can I stop this happening? In this particular case there is no URI in the address bar but on other functions there is.

You should just check if the contents in the database exist, if they don't, fill them. Otherwise don't run the function.

psuedo-code:

if !database.containsRecords
  fillDatabase()
end

On top of this, it is always good practice to redirect after a POST request. So you would want:

fillDatabase();
header("Location page.php");
exit();

Query the database on each page load and see if it has already been populated. If it has been populated then don't attempt to populate it again.

You should use the POST-redirect-GET pattern .

After updating the database, send an HTTP redirect to a separate page that displays the results.
Refreshing the browser will reload that separate page.

I assume you use a POST form to upload the file. You can include a hidden input field with an pseudo random unique id in your form. If the user resends the data via POST you can check if you already processed this request. Hidden fields are not save because a user might edit them, but you can detect accidental resubmits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM