Avoid opening the same page twice - php

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)

You could try with a cookie:
The first page load, the cookie is set(by the server for the session)
The next time the same page is loaded, it reads the cookie
If the cookie is there, do not overwrite session variables
I don't think the browser will be able to make a difference between a refresh and a load in another tab/window.

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.

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.

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!

Related

Does javascript autorefresh on webpage create extra load on server?

I have implemented auto refresh function on a webpage which refresh page after 2 second. Initially I wanted to do this using shall script which will hit that url in every 2 second. but server administrator advised me that it is not good to hit a page in every 2 second because it create extra load to server. Now I want to know if autorefresh also create the extra load to server same as shall script.
Thanks

Make php POST wait until page is complete before the browser navigates?

This is a complex question so I'll try and be precise.
I've experimented with AJAX but this form requires many changes to do it. I'd like to know if there are other options.
I have a form which takes a very long time to complete. Let's say the form exists on page A. The form submits and calls page B.
Page B looks like this, and gives the incorrect result (the page appears blank while loading):
<html>header</html>
<?php
longformresult()
?>
If I setup the page like this I get the result I am looking for (the page waits until the long function is done to load the page, allowing me to display a loading screen on page A).
<?php
longformresult()
?>
<html>header</html>
however this is where things get really tricky, the longformresult() can fail and break everything below it.
Is there some way I can tell php to wait until the page is fully loaded before sending the page, allowing me to have a loading screen on page A? Or prevent a die() from killing my page? I essentially need to delay the appearance of Page B, and actually just a sleep() is probably the best approach I've had so far:
<?php
sleep(4)
?>
<html>header</html>
<?php
longformresult()
?>
Edit: Conclusion (Not the fix I was looking for though)
I used ajax and removed 'Page B' entirely.
PHP waits by default to complete the function call before proceeding (see this previous answer), so PHP necessarily waits for the page to be fully loaded before returning.
AJAX would not require "many changes" if this is truly the behavior of the program. You would simply have a new file like C.php which returns the output of longformresult(), which you can later inject into your page.

Check text file every 20 seconds and get contents

I have a text file storing one string. I anticipate that the text file will be changing frequently, so in order to keep my page up to date, I would like to use PHP (preferably) to fetch data from the text file every 20 seconds so I can explode it into an array and use the contents accordingly. The variables would also need to update every 20s.
So: on page load, the contents are fetched and displayed. But the contents of the text file may be changed thus making the page outdated while a user may already have it open.
I tried META Refresh, but the whole page refreshes in the middle of browsing and interrupts the user.
Sorry for the confusing description, it's hard to explain. :)
I've searched the web for ages and not found an answer to my question. Please remember I am using a text file and not MySQL, since I'm only storing one string.
Thanks in advance.
If you want to stay with PHP, I'm afraid a refreshing HTML Meta is the solution :
<meta http-equiv="refresh" content="10; url=http://example.com/" />
Refresh the page every X seconds, so that the file gets reloaded.
Another way could be the use of frames, however I cannot seriously recommand it to you.
However, you can load a content without reloading the whole page, using Ajax. It allows you to perform a HTTP request to the server (using a Javascript code) and place its result on the current page, using Javascript as well. You could create a PHP script "my_string_parsed.php", which reads the file, and then parses/prints its content. Then, you could call this script through an Ajax request to http://yoursite.com/my_string_parsed.php, and place its result in a specified HTML tag on your page.
W3Schools.com provides an Ajax tutorial here : http://www.w3schools.com/ajax/
A warning concerning Ajax though : an Ajax content loading must never replace the typical HTTP behavior your browser and the server have. If the string in your file is the only content on your page, then the best solution would be the refreshing meta. Ajax should only be used to refresh parts of a page. Never the whole thing.
Why not using a database instead of a file. You could also use jQuery to update your page smoothly.

When to use AJAX

Let's say we have a page written in PHP. This page loads by it self a template with header, body and footer and print this out. Now let's say that in the body of this page we would like to start a loop and load some posts (messages taken from a database).
We also need the page to load new posts every 10 seconds, if any, without refreshing the page (classic AJAX). This ajax call will use JSON and AJAX and micro templates.
Now i'm just wondering:
Do we really need PHP to load posts the first time the page is loaded? Can't we just start that Ajax call and load posts with Ajax instead? (Notice that the existing ajax call would be kept as it is, since it loads posts starting from the latest loaded (in case of no posts, that would mean all posts).
If you did not understand my question don't hesitate to let me know.
In this situation I think the simpler approach is the let AJAX handle it, if you do let php load the initial messages, you'll have two places in code, that you'll need to maintain to perform identical jobs.
I think you are asking how you should load the posts the first time the page is accessed. If so: When the page firsts loads, have some PHP that prints out the existing posts. Then, add some JavaScript to update the page with new posts every 10 seconds. This is a matter of preference. You might want there to be no posts when the page first loads, and then use Ajax to get the existing posts once your page has loaded.
Edit:
I agree with jondavidjohn that you might be better off using pure Ajax. However, you could always isolate the code that fetches the pages into a separate function. That way, the script that generates the page calls the same function as the script that is called via Ajax.
The drawback with that technique is that it doesn't downgrade gracefully. So people with javascript disabled will not see any posts.
I'd recommend outputting some data with php - AJAX requires JavaScript which many people don't have activated.
Why not, instead of having the browser poll the server for new posts, have the browser push new content to the browser when it is available using the likes of node.js?
I designed my site with AJAX exclusively, and it works perfectly except for one rather major issue: Using AJAX requires JS to be enabled. Of course, if users trust your site, this is not a problem, but if they don't, then an AJAX solution won't work unless you put the entire page in a noscript tag.

How To Make A jQuery Async Multi-Response From One PHP Script Run

I have a run.php that has a button on it called "Run". Clicking it does a jQuery $.get() AJAX call back to a response.php on the server, and sends the result to a Javascript callback function getResponse(sData) inside run.php's HTML for display back on the browser. I want to have things such that as response.php runs through a list of tasks, it echoes a response back with the echo command and for getResponse to update a DIV with that status as it moves along. So, let's say I have 5 steps inside response.php, and therefore 5 echo statements back to getResponse().
I tried to get this to work, but what happens is that jQuery waits and then sends one single response all at once, rather than sending as it goes along with the 5 responses.
What's the technique?
The reason I ask is that I have a script that does something to a bunch of files. The first thing it does is a file count, so it updates my progress bar. Then, as it runs through files, it needs to increment my progress bar like every 1000 files.
I think there's no way to make that ajax call to have multiple response in just one call... but what I could suggest is you make a session on php... and in every steps on your tasks function, update that session... then make another ajax call that checks that session if any updates happened... if there is update then do what you have to do....
As you can't really get progress with xmlhttprequest, I suggest you can look into other ways of doing AJAX calls. One of them is through iframe. You can create hidden iframe, set it's sources to request.php and then periodically just check it's content. It should be possible since it's all it the same domain and restrictions does not apply.
iframe might work because it's not that different from normal browser window, meaning that it periodically applies data it gets into DOM even if request hasn't been finished yet. There's potentially might be problems with how different browsers do that, i.e. IE shows new content only if it got more than 4K or something. But it is possible to overcome that, I'm sure.
So, create new hidden iframe, add src attibute to your php script, make that script periodically write something to the client and on the client check what have been written and convert it to shiny GUI stuff.

Categories