Avoid opening the same page twice

By : tom
Source: Stackoverflow.com
Question!

I'm trying to find a solution to this problem: I have a page on a php application that can't be opened more than once to avoid session overwrite. I'm spending a lot of time without finding any solution!

The last one I tried is to use the jquery "load" and "unload" events on the window. It works fine if I open the same page in a new window or a new tab but it also blocks the page if I refresh it!

I really don't know how to go on! I thought this was a simple example of semaphore usage...but I can't code it in the right way.

Any suggestions? (both php and js solutions are welcome)

By : tom


Answers

Can't be opened more than once by the same user, I presume.

How did you use jquery's load and unload events? Brainstorming here, how about using load to set in the user's session a semaphore, which is removed by unload. Ofcourse I'm not sure if that event fires even when the browser crashes or similar unforseen technical issue. In that case you might have a stuck one that you'd need a specific timeout for, or to wait for the session to time out.

To fix that perhaps after the page loads have a timer that executes every 10 seconds, basically updating the semaphore sort of like "The page is still open", along with current timestamp. If on load the semaphore exists but the timestamp is older than 10 seconds, then the user is refreshing.

By : Fanis


The problem is that you do not have access to the end user's pages that are currently open in a browser. So the only solution is for you to keep tracking the pages the user opened/closed/switched to another page/etc. Even that isn't perfect as the user can open another browser process. So there is no perfect solution to this.

By : OTZ


sorry guys...you're right! A bit of code will help all of us :) suppose my script is script.php

in the html of script.php i put

$(window).bind('load',
function(){
    $.post(PATHTOLOCK.php);
});
$(window).bind('unload',
function(){
    $.post(PATHTOUNLOCK.php);
});

In the file PATHTOLOCK.php i do this:

$_SESSION['flag']=true;

And in the file PATHTOUNLOCK.php i do this:

$_SESSION['flag']=false;

At the beginning of script.php i put

if($_SESSION['flag']==true){
echo "error";exit;
}

If I open script.php in two windows/tabs everything works fine. If I refresh the page it doesn't work because I suppose the events sequence is the following:

  • click on refresh
  • unload event is not invoked because the page is not completely left
  • the script.php is reloading
  • the check at the beginning of script.php fails because flag=true
  • script.php goes in error
  • the unload event is invoked because the page is left and flag=false
  • click on refresh
  • now it works!

and so on...every two refresh it works!

By : tom


This video can help you solving your question :)
By: admin