It's a me Applez
It's a me Applez

Reputation: 91

Check if there is a session without using session_start()

I want to check if a person has an active session and redirect them to another page when they have one. However, I do not want to use session_start(), as that will place a cookie on the persons PC (I do not want to place cookies on peoples' PC when they're not logged in). Is there a way to check for an existing session, without placing a cookie on their PC?

Upvotes: 9

Views: 2687

Answers (4)

Ben Dixon
Ben Dixon

Reputation: 1

I found accessing session_name() to be unreliable for determining if someone is logged in.

You can set a cookie (only) when they are authenticated like this:

$user_id = 123; // Replace with the actual user ID
$expiration = time() + (30 * 24 * 60 * 60); // Cookie expires in 30 days
setcookie('user_id', $user_id, $expiration, '/', '', true, true);

Then you can check for that cookie like this

if (isset($_COOKIE['user_id'])) {
    $user_id = $_COOKIE['user_id'];
    // Use $user_id as needed
} else {
    // User ID not found in cookie, handle accordingly
}

It is not recommended to store user ID on the client side so make sure you're using SSL and implementing other security measures as necessary.

Upvotes: 0

MicronXD
MicronXD

Reputation: 2220

Test this first, but I think session_id() != "" will give true if there's a session and false if not.

Upvotes: 2

Problematic
Problematic

Reputation: 17678

You can either check against the function session_id(), which will return the current session ID for the user, or an empty string if no session exists:

if (empty(session_id())) {
  /* redirect or logic here here, example: */
  header('location:path/to/your/session/start/page');
  exit();
}

Or you can check that the session cookie/global variable is set (isset($_SESSION) or isset($_COOKIE[session_name()]. Doc for session_id() here

Upvotes: 2

Marc B
Marc B

Reputation: 360572

You can check for the existence of the session ID cookie, which the client would send back if it had been previous set elsewhere in your site:

if (isset($_COOKIE[session_name()])) {
   ... most likely there's a session available to be loaded ...
}

For added safety, you could then check for the existence of the session file (assuming you're using the default file-based handler) using session_save_path() and the session_name() to build up a path to pass into file_exists()

Upvotes: 9

Related Questions