Find out if a session with a particular id has expired

后端 未结 3 390
独厮守ぢ
独厮守ぢ 2021-01-28 09:13

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 tha

相关标签:
3条回答
  • 2021-01-28 09:28

    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

    0 讨论(0)
  • 2021-01-28 09:33

    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?

    0 讨论(0)
  • 2021-01-28 09:36

    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.

    0 讨论(0)
提交回复
热议问题