Check if PHP session has already started

2018-12-31 05:42发布

I have a PHP file that is sometimes called from a page that has started a session and sometimes from a page that doesn't have session started. Therefore 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?

If I use @session_start will it make things work properly and just shut up the warnings?

25条回答
妖精总统
2楼-- · 2018-12-31 06:42

This is what I use to determine if a session has started. By using empty and isset as follows:

if (empty($_SESSION)  && !isset($_SESSION))  {
    session_start();
}
查看更多
长期被迫恋爱
3楼-- · 2018-12-31 06:43

You should reorganize your code so that you call session_start() exactly once per page execution.

查看更多
谁念西风独自凉
4楼-- · 2018-12-31 06:45

Based on my practice, before accessing the $_SESSION[] you need to call session_start every time to use the script. See the link below for manual.

http://php.net/manual/en/function.session-start.php

For me at least session_start is confusing as a name. A session_load can be more clear.

查看更多
梦醉为红颜
5楼-- · 2018-12-31 06:47

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();
}
查看更多
步步皆殇っ
6楼-- · 2018-12-31 06:47
session_start();
if(!empty($_SESSION['user']))
{     
  //code;
}
else
{
    header("location:index.php");
}
查看更多
柔情千种
7楼-- · 2018-12-31 06:48

The only thing you need to do is:

<?php
if(!isset($_SESSION))
{
session_start();
}
?>
查看更多
登录 后发表回答