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?
Related Topics
Lazarus: Program without GUI - Many WSRegister Errors
Question | 6 Answers
SQLite: Check whether Table exists
Info | 0 Comments
Create Custom Error Pages for Website
Tip | 0 Comments
Delphi: Global Treatment of Errors (Exceptions)
Tutorial | 0 Comments
PHP Error: Cannot send session cache limiter - headers already sent
Question | 2 Answers
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
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.
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:
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
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:
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:
More about that here in the PHP-Manual.
2018-02-15 at 21:21
2019-08-27 at 06:56