
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
How to 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.
- Related Articles
- How to check if a user email already exists in Laravel?
- How to check if a Perl hash already contains a key?
- PHP program to check if a string has a special character
- How to check if a given key already exists in a Python dictionary?
- How to check if a table exists in MySQL and create if it does not already exist?
- Storing objects in PHP session
- How to check if a table already exists in the database with MySQL with INFORMATION_SCHEMA.TABLES.?
- How to check if a date has passed in MySQL?
- How to check if an element has a class in jQuery?
- How to check if the IText object has fill using FabricJS?
- How to check if the IText object has stroke using FabricJS?
- How to check if an Image has crop applied using FabricJS?
- How to check an empty table already in a MySQL database?
- How to check if dom has a class using WebDriver (Selenium 2)?
- How to check if a "lateInit" variable has been initialized in Kotlin?
