Check if PHP session sessionid is active

We block some resources for clients, the table that blocks the inventory contains the session identifier that blocked it along with other information about the client. When the session expires, we want to unlock this inventory so that other people can buy it. Since we are registering session_id () in the table, knowing this, is there a way to check if the session is active in PHP?

If we use the database to store the session, we can probably check if the row exists until the last activity, in memcached we can probably determine the session key and check it like this: in the file session, we can probably do the same, find out the file name for the session and check if the file exists.

Is there something that works everywhere, no matter where you keep the session?

+6
source share
9 answers

You can use session_id, and session_startfor this purpose.

$ids = [
            '135b29ef958a23418f2a804474787305', // active session
            '135b29ef958a23418f2a804474787306', // inactive session
            '135b29ef958a23418f2a804474787305', // active session
        ];

foreach($ids as $id)
{
    session_id($id);
    session_start(); 

    $status = isset($_SESSION['logged_in']); 

    print( ($status ? 1 : 0) . PHP_EOL);
    session_abort();
}

Check if there is always a session variable set. To make sure this is not a new session.

You will need to check if this does not reset the lifetime counter in the session. On my system, this does not affect life expectancy until something changes in the session

Edit: Updated using session_abortfor looping and checking multiple session identifiers

+3
source

Check if a session exists in the session folder:

echo ini_get('session.save_path');

for example, in the folder session id file:

sess_l75lm4ktlhvlu566n8i6do8k71

():

ini_set ('session.cookie_lifetime', 100)

session_destroy(); :

        if (file_exists($sessionfile)) {
        echo "exists";
    }else{
        echo "not exist"
    }

js ( firefox):

    <script type="text/javascript">
    // alert(document.cookie);

    window.onbeforeunload = function () {
    return "Do you really want to close?";
    };
    window.onunload = function () {
    return "Do you really want to close?";
    };

    $(window).on('beforeunload', function(){ alert ('Send post to unlock product')});
    $(window).unload( function () { alert("'Send post to unlock product'"); } );
</script>
+3

session_id, session_start ..

, . . (www-data) cli script, , , . .

, .

, , 20 . , , .

  • last_activity session_id ( )
  • NOW ( $row->touch() - docs).
  • crontab last_activity < NOW - delta, delta - .

, .

P.S. , , , . , .

+2

, PHP . , , , , .

, PHP , .

PHP, . . 'session_start, . , :

PHP 4.3.3, session_start() , , E_NOTICE. , .

- , , . , PHP , , .

, , . , , .

. ini_get('session.save_path');. script , -.

script , .

+2

, , , .

+1

beforeunload, Javascript. Javascript , AJAX , ( jQuery):

$(window).bind("beforeunload", function() { 
    $.ajax({
        url: "http://example.com/destroySession.php"
    });
});

, sessionID, PHP session_destroy(). :

<?php

// Load your config bootstrap / etc.

session_start();

// Unlock target inventory items

session_destroy();

?>
+1

session_status PHP v5.4 , , .

session_id:

session_id() (""), ( ).

+1

, (, last_activity) , , , , . :

$sessionId = get_session_id_that_locked_the_item_from_db();

if(session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
// get current session id.
$current_id = session_id();
// renew activity.
echo 'Renewed my activity.';
$_SESSION['active'] = 1;
// Close the current session
session_write_close();

if($current_id === $sessionId) {
    // the current user has locked the item.
}
// Check if the var active of this session exists.
elseif(!checkSessionlastActivity($sessionId, $current_id)) {
    // Show the inventory item.
    showInventoryItem();
    // Lock inventory when the item is selected(eg added to basket).
    if('I want to lock the item') {
       lockInventoryItem($current_id);
    }
}
else {
    echo 'Item is locked.';
}

function checkSessionlastActivity($id, $current_id) {
    // switch session to the one that locked the item.
    session_id($id);
    session_start();
    // get session is active.
    $active = ( isset($_SESSION['active'])? $_SESSION['active']: null);
    // Close the session.
    session_abort();
    // restore current session.
    session_id($current_id);
    session_start();

    if($active !== null) {
        return true;
    }
    return false;
}

function lockInventoryItem($current_id) {
    put_my_session_id_to_db($current_id);
}

function showInventoryItem() {
    echo 'You can select item';
}

. , . php.

: . , , , , . , , .

, , , (session.gc_maxlifetime, session.gc_probability session.gc_divisor), .

+1
// correct way
$id = 'abc';
session_id($id);
session_start();
$isActive = (session_status() === PHP_SESSION_ACTIVE);
session_write_close();
var_dump($isActive);

// tricky way (root required)
$id = 'abc';
$isActive = false;
$sessionTimeout = (int)ini_get('session.gc_maxlifetime');
$rdi = new RecursiveDirectoryIterator(session_save_path(), FilesystemIterator::SKIP_DOTS);
$rii = new RecursiveIteratorIterator($rdi);
$ri = new RegexIterator($rii, preg_quote("/sess_$id/"), RegexIterator::MATCH);
/**
 * @var $fileInfo SplFileInfo
 */
foreach ($ri as $fileInfo) {
    $expiredAt = $fileInfo->getMTime() + $sessionTimeout;
    $isActive = $expiredAt > time();
    if ($isActive) {
        break;
    } 
}
var_dump($isActive);

, - .

http://php.net/manual/en/function.session-set-save-handler.php

Based on your profile, you know yii. There is a good implementation example:

https://github.com/yiisoft/yii2/blob/master/framework/web/DbSession.php

https://github.com/yiisoft/yii2/blob/master/framework/web/Session.php#L97

https://github.com/yiisoft/yii2/blob/master/framework/web/Session.php#L148

+1
source

Source: https://habr.com/ru/post/1015054/


All Articles