Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP clear browser cache to avoid form data resend after refresh

I'm developing a PHP-MySQL app that enables registered users to enter text comments. Problem is:

  1. User sign-in into the web site - OKAY
  2. User presented with a form to submit text comment - OKAY
  3. User enters text comment and submits - OKAY
  4. I have a routine that sanitize the comment & save it into MySQL (with userid, textcomment, datetime stamp) & present back the user that his/her comment is entered - OKAY
  5. User decides to refresh browser - a duplicate comment is entered - BAD!

I was thinking 3 options:

  • OPTION 1: Routine that checks: last time user posted comment, and if so, check if this is a duplicate. If duplicate then display error message.
  • OPTION 2: Routine that does not allow a user to post too quickly. So basically do not allow postings of comments within 1 minute or so. So if browser is refreshed the comment will be ignored.
  • OPTION 3: Manipulate the browser cache to clear out its contents so when refreshed no duplicate will be entered.

Now in the context of my application, my concerns with OPTION 1 and OPTION 2 is performance PHP-MySQL since I already have various queries within the same page that push/get data from databases. So OPTION 3 may target the issue differently.

Questions is: If I go for OPTION 3 can this be considered a Best Practice? meaning clearing the browser cache is the best most effective solution? I have read that there are consequences too? your thoughts are appreciated!

like image 970
Jorge Avatar asked Nov 16 '10 16:11

Jorge


People also ask

Why does cache return after clearing?

You might notice that when you clear cache, it comes back eventually. This is normal; over time, apps will build up cache again based on your usage. Because cache is useful, you shouldn't worry when an app builds up cached files. Clearing cache shouldn't log you out of apps or cause any other major changes.

How do I clear all cache in PHP?

The clearstatcache() function clears the file status cache. PHP caches data for some functions for better performance. If a file is to be checked several times in a script, you probably want to avoid caching to get correct results. To do this, use the clearstatcache() function.


1 Answers

Just do a redirect after submitting data to the database. It's a common practise.

An http redirect instructs the browser to issue an http GET for the url specified (as opposed to the http POST that is used to submit the form) . If you do this right after you have inserted data into the database, when the user refreshes his browser nothing will happen other than him seeing the same page again.

This question on SO tells how you redirect with php.

like image 160
Klaus Byskov Pedersen Avatar answered Sep 23 '22 02:09

Klaus Byskov Pedersen