How to check if php session is already started or not?

0 votes

Hii,

When I have session_start() on this script I sometimes get the error message for "session already started". For that I've put these lines:

if(!isset($_COOKIE["PHPSESSID"]))
{
  session_start();
}

but this time I got this warning message:

Notice: Undefined variable: _SESSION

Is there a better way to check if session has already started?

Apr 1 in PHP by kartik
• 11,290 points
49 views

1 answer to this question.

0 votes

Hello kartik,

Use session_id(), it returns an empty string if not set. It's more reliable than checking the $_COOKIE.

if (strlen(session_id()) < 1) {
    session_start();
}

Addition: For all php version

if ((function_exists('session_status') 
  && session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
  session_start();
}

Thank You!!

answered Apr 1 by Niroj
• 22,790 points

Related Questions In PHP

0 votes
1 answer

What is Php Mysql Database? How php connect to database?

Hello kartik, MySQL is the most popular database ...READ MORE

answered Feb 25 in PHP by Dey
90 views
0 votes
1 answer

How to Validate Form Data With PHP?

Hey @kartik, The first thing we will do ...READ MORE

answered Feb 13 in PHP by Niroj
• 22,790 points
93 views
0 votes
1 answer

How to validate E-mail and URL of Php form?

hey, The code below shows a simple way ...READ MORE

answered Feb 13 in PHP by manish
81 views
0 votes
1 answer

Error: Global Variable is not accessable to local function

Hey kartik, A variable declared outside a function has a ...READ MORE

answered Feb 19 in PHP by Niroj
• 22,790 points
36 views
0 votes
1 answer

How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18 in Laravel by Niroj
• 22,790 points
434 views
0 votes
1 answer

What is redirection in Laravel?

Named route is used to give specific ...READ MORE

answered Mar 18 in Laravel by Niroj
• 22,790 points
62 views
0 votes
1 answer

How to install Laravel via composer?

Hello, This is simple you just need to ...READ MORE

answered Mar 23 in Laravel by Niroj
• 22,790 points
64 views
0 votes
1 answer

What are named routes in Laravel and How can specify route names for controller actions?

Hey @kartik, Named routing is another amazing feature of ...READ MORE

answered Mar 23 in Laravel by Niroj
• 22,790 points
151 views
0 votes
1 answer

What is a Cookie? How to create Cookies With PHP?

A cookie is often used to identify ...READ MORE

answered Feb 13 in PHP by Niroj
• 22,790 points
106 views
0 votes
1 answer

How to retrieve or obtain data from the MySQL database using PHP?

Hello kartik,  Actually there are many functions that  ...READ MORE

answered Mar 27 in PHP by Niroj
• 22,790 points
33 views