Home » Php » php – Check if there is a session without using session_start()

php – Check if there is a session without using session_start()

Posted by: admin July 12, 2020 Leave a comment

Questions:

Hey guys, this will be my first question on Stackoverflow.

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?

Thanks in advance.

How to&Answers:

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()

Answer:

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

Answer:

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