Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JussiMannisto's avatar

Getting session ID from the cookie

Hi,

I'm implementing two features in the front-end: a warning when user session is about to expire, and a login page redirection when it has expired.

User sessions are stored in a database. I'm polling the session status periodically with API requests. In the back-end, I'm reading session ID directly from the cookie. I can't access it normally by including the StartSession middleware because every API request would extend the session by updating the last_activity column, keeping the session alive forever.

I'm decrypting the session ID like this:

$sessionId = Crypt::decrypt($request->cookie(config('session.cookie')), false);

However, this returns a two-part string with a pipeline separator:

68f8331576ee7fb67b9ad59xxxxxxxxxxxxxxxxx|lkaCQMKOmp4QRAwfUAOm9FOxxxxxxxxxxxxxxxxx

What is this format? The second part is the session ID, but what does the first part mean?

0 likes
2 replies
Braunson's avatar

You can get the session ID via the session helper... session()->getId(). I don't believe you can check the time left of the session before expiry. I'd suggest checking this post on StackOverflow for a workaround if you want to track session time left.

Looking at the docs, you'll see the Database session driver tracks last_activity, using the SO link above and this knowledge you could implement a last_activity on the users table while using the cookies session driver.

If you want to redirect after a session has expired, you need to implement a poll/ajax call that calls every x seconds or minutes that pings an endpoint and checks if the user is logged in via say auth()->check() if false, then on your frontend you can redirect them or show them a login modal.

JussiMannisto's avatar

That won't work. You don't get the correct session ID from session()->getId() unless you include the \Illuminate\Session\Middleware\StartSession middleware. And if you do that, the session TTL gets extended as last_activity is automatically updated. The API calls would then keep the session alive forever, which is something you don't want.

You definitely don't want last_activity on your users table since a user may have multiple sessions on different devices. It should be a sessions table column (as it is).

I implemented the API and polling. I only have an issue with the session ID string I get from decrypting it from the cookie: why is it in that format and what does the first part of the string signify?

I can of parse the session ID from it, get the correct session from DB and check its TTL. But I can't deploy the code to production until I understand the format fully.

Please or to participate in this conversation.