
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if PHP Session Has Already Started
In PHP,we utilize session_start() an inbuilt function to start the session .But the problem we face in a PHP script is if we execute it more than once it throws an error. So here we will learn how to check the session started or not without calling session_start() function twice.
There are two ways to follow to resolve this problem.
For below PHP 5.4.0 version.
Example
<?php if(session_id() == ''){ session_start(); } ?>
Explanation
If the session not started this code above will always start the session in the PHP script.
In the second method, we can utilize the function session_status(), which returns the status of the present session. This function can return three integer values, which all are predefined constants. These are:
- 0 – PHP_SESSION_DISABLED: Sessions are currently disabled.
- 1 – PHP_SESSION_NONE: Sessions are enabled, but no session has been started.
- 2 – PHP_SESSION_ACTIVE: Sessions are enabled and a session has been started.
Example:
<?php if (session_status() == PHP_SESSION_NONE) { session_start(); } ?>
Explanation
The above code checks whether the session started or not, if not started this will start the session in the PHP script.
Note
session_status() function only runs in PHP 5.4.0 version or above.