Find out if a session with a particular id has expired
I am creating an upload feature that stores a user uploaded file on the server with the user's session-id as its name. Now, I want to keep this file on the server only till that session is active.
So, my question is, how can I determine from the session-id, whether a session is active or expired so that in the la开发者_JS百科ter case I can safely delete the user uploaded file.
This I want to do as a cleanup at particular intervals maybe by using a cron job, though I have never used it before.
You can't just rely on session.gc_maxlifetime because after this time the session is marked as garbage and the garbage collector starts only with a probability of 1% by default ( session.gc_probability).
The better approach IMHO is to handle yourserlf the expired data.
You can for instance start the time and save it into a session variable:
<?php $_SESSION['last_seen'] = time();//Update this value on each user interaction. ?>
Later..via cron you can do something like this:
<?php
//Get the session id from file name and store it into the $sid variable;
session_id($sid);//try to resume the old session
session_start();
if (isset($_SESSION['last_seen']) && $_SESSION['last_seen'] > $timeout){//Session is expired
//delete file
session_destroy();
}else if (!isset($_SESSION['last_seen')){ //already garbaged
//delete file
session_destroy();
}
?>
Not tested...just an idea
I'm trying to do the exact same thing. One solution would be to define a custom garbage collector function with session_set_save_handler()
. In this custom function you would delete the uploaded files associated with the session and then delete the session from disk. The only problem I see it's that you will have to define the rest of the session handlers as well:
bool session_set_save_handler ( callback $open,
callback $close,
callback $read,
callback $write,
callback $destroy,
callback $gc )
This is easy if you don't rely on PHP to handle sessions. Is there a way to call the default handler functions of PHP from a custom handler function?
Intervals can be made like this - someone opens your web -> php script is running -> it checks if files is time-outed -> delete time-oted files
And no CRON needed :-)
It is nearly impossible to determinate due to lack of information if user closed or not the browser window ( if he don't closes it but turn sleep mode on and come back in 2 days - session is still active AFAIK ) - only idea to slove this problem in best manner this is to use own session engine with AJAX checking.
精彩评论