Detect back button pressed?

hi guys,

I know you cant disabled the back button, and I don't really want to -  but is there any way to stop a code block running again if a user clicks back?

I am writing a quick and dirty (low budget) wizard in PHP for one of my clients and it post’s back to itself until it follows X amount of steps. Everything is running as I’d wished but I just want to catch this eventuality.

Many thanks.

I guess it is more javascript issue: something like that?

In PHP you can just check in session latest request of that user to see if they are the same, I guess.

I haven’t tried this (so consider it a theory), but if you set your Cache header to no-cache so the pages can’t be cached, the browser might now allow the back button to be invoked, or if it did, it would show a message stating the page has expired and to refresh to get the latest version of it.

Worth a shot :slight_smile:

What I really want is to distinguish between the submit button being pressed to go forward (postback), and the back button being pressed on the browser.

I have an Object stored in a session variable which has data added to it with every step, if one were to go backwards the data would be added twice and thats what id like to avoid is possible.

I can understand that :slight_smile: The problem you will face (that hopefully using the Cache header with no-cache will solve) is the browser is serving a cached copy of the page, so your script isn’t executing to load that previous step (so nothing in your script will block it), but you could check when the form is submitted again, does the data already exist and should I update it?

Or you can try using no-cache and verify that the browser doesn’t load a cached version to the user.

Will give that a bash tommorow :slight_smile: If any other PHP pro’s have any suggestions as well they are most welcome :slight_smile:

Well, in the short term;
Write a ‘executed’ code into the session; dont execute the code block if the session holds that value.
This is obviously easier to do with form input.

For example:

 <input type='hidden' name='formid' value='<?php echo time(); ?>'>

if(!isset($_SESSION[$_POST['formid']])) {
 $_SESSION[$_POST['formid']] = '';

If they push the back button (and thus, resubmit the form), $_SESSION will hold the value of formid already, and not execute the code.

Thats a damn good idea, im going to try that - will let you know how I get on!!