Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you check if a PHP session exists?

Tags:

php

session

Just wondering how to check if a PHP session exists... My understanding is that no matter what, if I am using sessions, I have to start my files with session_start() to even access the session, even if I know it already exists.

I've read to user session_id() to find out if a session exists, but since I have to use session_start() before calling session_id(), and session_start() will create a new ID if there isn't a session, how can I possible check if a session exists?

like image 319
ARW Avatar asked Oct 28 '12 23:10

ARW


People also ask

How do you check if there is a session in PHP?

You can check whether a variable has been set in a user's session using the function isset(), as you would a normal variable. Because the $_SESSION superglobal is only initialised once session_start() has been called, you need to call session_start() before using isset() on a session variable.

How check session is empty or not in PHP?

If you want to check whether sessions are available, you probably want to use the session_id() function: session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists).

What is session status in PHP?

PHP - session_status() Function Sessions or session handling is a way to make the data available across various pages of a web application. The session_status() function returns the status of the current session.

Can PHP track user sessions?

Sessions and PHPPHP allows us to track each visitor via a unique session ID which can be used to correlate data between connections. This id is a random string sent to the user when a session is created and is stored within the user's browser in a cookie (by default called PHPSESSID).


2 Answers

In PHP versions prior to 5.4, you can just the session_id() function:

$has_session = session_id() !== '';

In PHP version 5.4+, you can use session_status():

$has_session = session_status() == PHP_SESSION_ACTIVE;
like image 131
xenak Avatar answered Sep 22 '22 08:09

xenak


isset($_SESSION)

That should be it. If you wanna check if a single session variable exists, use if(isset($_SESSION['variablename'])).

like image 35
Simon Carlson Avatar answered Sep 21 '22 08:09

Simon Carlson