Session is not active even when PHPSESSID is set and session_start() has been called PHP

Viewed 507

I am trying to create a page that logs out the users on my website, but when I try to reinitialize the session, my page keeps saying Warning: session_regenerate_id(): Cannot regenerate session id - session is not active. The code that starts the session:

try {
  if (!isset($_SESSION) or session_id() == "") {
    session_start();
    if (!isset($_COOKIE['auth']) or $_COOKIE['auth'] != 'NO') {
      $_COOKIE['auth'] = 'NO';
    }
  }
} catch (Error $e) {
  echo "Caught Error: $e";
}

The logout page code:

try {
    unset($_SESSION);
    session_regenerate_id(true);
} catch (Error $e) {
    echo "Caught Error: $e";
}

There are not session_destroy()s or anything like that anywhere else on my website (as mentioned here), and I can see that the PHPSESSID cookie is set and after clearing the cookies gets set again after a page refresh.

1 Answers

Just know that sessions should be started right at the beginning of the code

So do something like this:

<?php

    session_start();
    session_regenerate_id(true);

    if($_SESSION['name_of_the_session'] == false){
        header("Location: please_make_login.php"); //If doesn't exists the session, redirect user to the login page
        exit();
    }
   
    try {
        if (!isset($_COOKIE['auth']) or $_COOKIE['auth'] != 'NO') {
          $_COOKIE['auth'] = 'NO';
        }
      }
    } catch (Exception $e) {
      echo "Caught Error: " . $e->getMessage();
    }

Logout

<?php

    session_start(); //It'll see if exists a session
    session_destroy(); //Then will destroy the session
    header("Location: index.php"); //And redirect to a page named index.php & finish the process
    exit();

If you want to work with sessions, then initialize them first in every PHP script, and after initializing the session, regenerate the id, a quick example:

<?php
 
 session_start();
 session_regenerate_id(true); //I recommend to use true

 $some_variable = $_SESSION['name_of_the_session'];

 //Don't forget to check if the session exists, if the user really started a session!
 
 if($some_variable == false){
   header("Location: please_make_login.php"); //Redirect the user to a page because the user doesn't started a session
   exit();
 }

 echo $some_variable; //Echo the value of the session, it'll only echo if really exists
Related