In PHP, we use the built-in function session_start() to start a session. But the problem we have with the PHP script is that if we execute it more than once, it throws an error. So, here we will learn how to check if the session has been started without calling the session_start() function twice.
There are two ways to solve this problem.
For PHP versions below 5.4.0.
<?php if(session_id() == ''){ session_start(); } ?>
The above code will always start the session in the PHP script if the session is not started.
In the second method, we can use the function session_status(), which returns the status of the current session. This function can return three integer values, which are predefined constants. They are:
<?php if (session_status() == PHP_SESSION_NONE) { session_start(); } ?>
The code above checks if the session has been started, if not it starts the session in a PHP script.
session_status() function only runs in PHP version 5.4.0 or higher.
The above is the detailed content of How to check if PHP session has been started?. For more information, please follow other related articles on the PHP Chinese website!