How to close a session in PHP when the browser is closed? - php

I need to close a session when the browser is closed, when it crashes, when a PC restarts, and so on.
I know there is cookie solution, but I need something secure, server side, because the user can delete the cookie.

You dont have to. The garbage collector will clean up your sessions.
The php ini setting session.gc_maxlifetime determins how long a session can remain active.
When this value is exceeded the session is automatically removed.

This can not be done the way you imagine it.
You can not directly react to such an event in php.
The closest you can get is using ajax to keep the session alive.
Create a small php script which does nothing but update $_SESSION['last_request'] lets call it pulse.php
Insert a javascript in you pages which sends a request to
yourdomain.com/api/pulse.php every 60 seconds.
Check if the last request uis older than 70 seconds on every request
if it is start your clean up script and kill the session.
If the browser crashes your cleanup script will not run. The session will timeout the usual way unless you get a request after more than 70 seconds but before the session expires.
You can fix this if you store the session data in a database.
Then you can run a worker or a cronjob which regularly checks if there are sessions where the last request was more than 70 seconds ago.
Why 70 seconds? If you expect a request once per minute you should allow some time for klatencys or slow hardware on the client side.

Hi You don't need to close session. because its default behavior of session that it destroy the session when user close the browser. And we can alter this behavior by changing lifetime of session in php.ini file by doing
session.cookie_lifetime = 0. Otherwise by default
when you reopen the browser there will be no data in session.

cookie delete automatic when user run crashed brouser.
in php no way to know when user close brouser.
some not easy way it's websocket and long poling connections, but it's not easy to configuration and not good idea.

Related

Yii Session Timeout and Periodic Server Short Polling

I am using short polling in jQuery to periodically (5 mins) check the server for notification updates. I also have a session timeout set on the server after which i would like the user to get automatically logged out. The trouble is that the polling causes the session to extend and the user never gets automatically timed out.
Is there any way in Yii to avoid updating the session for this call alone? Am I missing something?
I am thinking of moving the server side script for this call alone to a standalone PHP script but there would be maintenance overhead associated with this so I am kind of hoping that there is something I can do within Yii to work around this. Thanks.
I suggest to have a session variable for last time of activity
, every time an activity that counts as an activity, update this
and in case of this special request, don't update this and check if the time period is over, manually log user out and destroy it's session
Yii::app()->user->logout();
unset($_SESSION);

Requests from same client being queued in Apache, PHP stack [duplicate]

session must be synchronized. When A writes/saves to session B or another A is put on wait. Which is a must for file based session handling.
But once A has loaded the session (but now saved its modifications) B should also be allowed to load the same session. because loading will open the file and bring the file contents in memory and close.
Is there any reason to block all other scripts during the whole time A loads session and A saves the session. can't the synchronization be done only with save handler ?
So two PHP scripts can never work concurrently If they share the same session.
for example seslock.php
<?php
header('Content-Type: text/plain');
session_start();
if(isset($_GET['wait'])){
sleep(30);
echo "waiting\n";
}else{
echo "No Waiting\n";
}
?>
done
visit seslock.php will respond immediately but seslock.php?wait will take 30 seconds to respond. But the problem is if you request seslock.php?wait first and only seslock.php second. event the non-sleep block will ask you to wait for 30 seconds too.
Why it block is not my question. I am asking why it blocks start to save ? instead of blocking only save ?
Possible duplicates:
How does session_start lock in PHP?
Why does session_start cause a timeout when one script calls another script using curl
session_start hangs
How to kill a PHP session?
... And many ;)
Edit
The reason why it blocks is because the session file is being read and it might be modified at any point of time when the first script is running, hence the lock.
The remedy to this could be a session_write_close() as pointed by this post
How to prevent blocking php requests, by Konr Ness
The default PHP session handler is made to serialise session changes for each session id. This has the benefit of a guaranteed consistent session state across your scripts.
You can give up this advantage by running session_write_close() right after session_start(). This also makes your session read-only though.
Alternatively you can write your own session handler without locking.

When does a web server clear the PHP session identifier?

Background:
I am trying to write a script that connects on a regular basis to a web server and checks if some information on a specific page was changed. I already got this working using a combination of bash (for scripting), curl (for the actual connection) and crontab (for the scheduling).
Since the server requires authentication, I first used curl to do a POST request on the login page with my credentials and saved the cookie file (containing the PHPSESSID). Now i can use the cookie file when doing the request for the actual web page I want to check.
Question(s):
When does the server actually clear the PHPSESSID i set with my first request? I imagine it must do this sometime, otherwise it would crash because it keeps storing information about every single session that was ever started.
If the PHPSESSID is cleared on closing the browser is there some way i can simulate that even using curl?
It's a little more complicated than just "when it's cleared"
A session has a lifetime in PHP. The default is 24 minutes. That means that after you connect to a website, your session is valid until
You close the browser (which won't be simulated with cURL unless you just drop the cookies)
OR
24 minutes pass
Each time you load a page and the server calls session_start() that expiration time will be bumped an additional 24 minutes (technically speaking it's actually bumped 24 minutes at the end of the script execution on pages where session_start() is called).
When that cookie actually expires, your session is no longer valid, and $_SESSION will be empty on the server side. But your data is still on the server until the next time that the server performs a session garbage collection cycle to clear out expired sessions which, depending on the session handler in use on the server, may or may not actually delete your data. A bank, for example, might send the data off to an archive server in case they ever need the records.
The server removes the session after the session timeout-time has passed after the last request. This is by default 1440 seconds (24 minutes), it can be changed in php.ini file.
The session is not flushed serverside on closing the browser, the client loses his session data though, since the browser deletes his local memory of the session. But if you keep your sessionid somewhere safe you can use it later on again, if you stay within the timeout frame of course.
This is exactly how session hijackings work, they get your sessionid in some way and can then set this sessionid on their own machine and continue your session.

can php session expire while sending a post ?

Basically, a php session won't expire while a user is surfing on a website. But "while the user is surfing on the website" means that there are get and post requests. Nevertheless, i can't figure out if there has to be new requests, or if one active request is enough to maintain the session…
For instantce, i have a big file upload by post. It could then take hours. Will the session expire or not ?
The lifetime of a session depends on the ini setting session.gc-maxlifetime. Every access to the session (read and write) resets the timer. After the timeout, when the session garbage collector runs, the session values are destroyed.
The default value is 1440, which means 24 minutes. So if you have hits that access the session in any way at least every 24 minutes, the session values will stay.
If you need the session to stay alive longer than that, you can extend the timeout with ini_set (use before session_start()), for example:
ini_set('session.gc_maxlifetime', 24*60*60); // 24 hours
It shouldn't. Usually when I work with $_SESSION's, they last for a day or so. But it might on some servers. In that case you need to add cookies, too. With cookies you can exactly manipulate the time the person can be online for.

PHP Session expire event

I am trying to make some changes to an opensource project. I want to keep track of when users log in and log out.
Right now I change their login status in db when they login or manually log out. The problem right now is that I cannot find out if the user just closed their browser without pressing on logout button.
For this reason I need to trigger a function that will change database every time the user's session expires.
I've tried session_set_save_handler in PHP, but it looks like I need to override the whole session behavior. What I am looking for is to keep default session behavior and just add functionality when the user's session expires. Is there a way to do that?
I did something really nasty once. Every time a session was "updated" by a page refresh / fetch / etc., I updated a timestamp on a DB row. A second daemon polled the DB every 10 minutes and performed "clean-up" operations.
You won't find any native PHP facilities to achieve your goal. Session timeout doesn't run in the background. You won't even know if a session is timed out, unless a timed out session attempts another access. At this point, nearly impossible to trap, you can make your determination and handle it appropriately.
I'd recommend a queue & poll architecture for this problem. It's easy and will definitely work. Add memcached if you have concerns about transaction performance.
I presume you're using standard PHP file-based sessions. If that's the case, then PHP will do its own garbage collection of stale sessions based on the session.gc_* configuration parameters in php.ini. You can override those to disable the garbage collector completely, then roll your own GC script.
You could either check the timestamps on the files (quick and easy to do in a loop with stat()) to find 'old' sessions, or parse the data in each file to check for a variable that lists the last-access time. Either way, the session files are merely the output of serialize($_SESSION) and can be trivially re-loaded into another PHP instance.
What about window close event on javascript. So basically session is destroyed when all of the windows of the session site are closed. So, when the last window is closed ( this is checked via additional js checking ) send ajax request to server.

Categories