PHP how to check if session already exists

Posted on Sep 26, 2022

Learn how you can check if a session already exists or started in PHP

Photo from Unsplash

To check whether a session already exists or started in PHP, you can use the isset() or session_status() function.

The session_status() function will return PHP_SESSION_ACTIVE when you have sessions enabled and one exists.

You can use this function inside an if block to check your session as follows:

// 👇 enable PHP session

// 👇 check if session exists. returns true
if (session_status() == PHP_SESSION_ACTIVE) {
    print "session already exists";

When you have called the session_start() function, then a session has been created by PHP.

Besides using session_status(), you can also use the isset() function and check the $_SESSION superglobal like this:

if (isset($_SESSION)) {
    print "session exists";

Using the isset() function also allows you to check if a specific key exists in the $_SESSION array as shown below:

// 👇 check if userid key exists in $_SESSION
if (isset($_SESSION['userid'])) {
    print "session exists";

Depending on your situation, you can choose to use the session_status() or isset() function to check if a session exists in PHP.

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.