00 Votes

PHP: Check if session already exists - Prevent error "A session had already been started"

Question by Guest | 15.02.2018 at 10:20

I am working with sessions in one of my PHP scripts. From time to time, unfortunately, it happens, that apparently already a PHP session exists, after revoking session_start(). This results in the following error message:

Notice: A session had already been started - ignoring session_start()

How can I prevent this error message and check whether a session already exists and call session_start() accordingly only if there is no session yet?

ReplyPositiveNegativeDateVotes
Avatar
02 Votes

You can easily check with isset(), if there is already a session or in your case, if no session is open.

You do that as follows:

if (!isset($_SESSION)) { 
  // no session has been started yet
  session_start(); 
} 

However, the best solution would be to (re-)structure your code so that session_start() is reliably invoked only once, for example, only every time you start your script. With a good code design, there should not occur any multi-call to session_start().
15.02.2018 at 12:23

ReplyPositive Negative
Avatar
11 Vote

You can also use the PHP function session_status() to check if there is currently a session. If a session is open, you will get back PHP_SESSION_ACTIVE  from session_status(). So you can write:

if (session_status() !== PHP_SESSION_ACTIVE) {
  session_start();
}

This checks if session_status() is not equal to PHP_SESSION_ACTIVE (= one session is active) and then starts a new session.

Other return values of session_status() are:

  • PHP_SESSION_DISABLED: Sessions are disabled.
  • PHP_SESSION_NONE: Sessions are enabled, but no session exists.
  • PHP_SESSION_ACTIVE: Sessions are enabled, and a session exists.

More about that here in the PHP-Manual.
15.02.2018 at 21:21

ReplyPositive Negative
Avatar
00 Votes

if (session_id() == '' || !isset($_SESSION)) {
  session_start();
}

27.08.2019 at 06:56

ReplyPositive Negative
Reply

Related Topics

"G" or "E" sign on my mobile
Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.