Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Check if PHP session has already started?
In PHP, we utilize session_start() to start a session. However, calling this function multiple times in the same script throws an error. Here we will learn how to check if a session has already started without calling session_start() twice.
There are two methods to resolve this problem, depending on your PHP version.
Method 1: Using session_id() (PHP < 5.4.0)
For PHP versions below 5.4.0, use the session_id() function to check if a session exists −
<?php
if(session_id() == '') {
session_start();
}
// Your session code here
$_SESSION['username'] = 'john_doe';
echo "Session started successfully!";
?>
The session_id() function returns an empty string if no session has been started, making it perfect for conditional session initialization.
Method 2: Using session_status() (PHP ≥ 5.4.0)
For PHP 5.4.0 and above, use the session_status() function which returns the current session status −
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Your session code here
$_SESSION['user_id'] = 123;
echo "Session is active!";
?>
Session Status Constants
The session_status() function returns one of these predefined constants −
| Constant | Value | Description |
|---|---|---|
PHP_SESSION_DISABLED |
0 | Sessions are disabled |
PHP_SESSION_NONE |
1 | Sessions enabled, but not started |
PHP_SESSION_ACTIVE |
2 | Sessions enabled and started |
Complete Example
Here's a practical example showing both methods in a reusable function −
<?php
function safe_session_start() {
if (version_compare(phpversion(), '5.4.0', '>=')) {
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
} else {
if(session_id() == '') {
session_start();
}
}
}
// Usage
safe_session_start();
$_SESSION['message'] = 'Session started safely!';
echo $_SESSION['message'];
?>
Conclusion
Use session_status() for modern PHP versions (5.4.0+) and session_id() for older versions. Both methods prevent the "session already started" error effectively.
