22 Votes

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

Question by Guest | Last update on 2023-03-09 | Created on 2018-02-15

I am working with sessions in one of my PHP scripts. Unfortunately, from time to time, 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
13 Votes

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

You can 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().
Last update on 2023-03-09 | Created on 2018-02-15

ReplyPositive Negative
33 Votes

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.
2018-02-15 at 21:21

ReplyPositive Negative
-11 Vote

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

2019-08-27 at 06:56

ReplyPositive Negative
Reply

Related Topics

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.