“Undefined variable: _SESSION” VS. “A session had

2019-07-03 02:18发布

Hey. I have some php scripts. In one of them i have the code session_start(), and when I in another script again have session_start() i get the notice:

Notice: A session had already been started...

Thats logical. But when I remove it I get the error/notice:

Notice: Undefined variable: _SESSION

Why? And how do I fix it? The scripts works fine when I have session_start() two places in the script (only get an little notice), but doesn't work at all when I doesn't have two session_start().

Is the only solution to have an

error_reporting(E_ALL ^ E_NOTICE);

in my script? And isn't that bad practice to just ignore notices?

Edit:

Parts of my code:

            try {
            //session_start();

            $STH = DB::prepare  (   "UPDATE users SET DJ_name=?, DJ_showname=? WHERE id=?" );
            $STH->execute(array($_POST['DJ_name'], $_POST['DJ_showname'], $_SESSION['userid']));

            pre_dump($_SESSION);

            $_SESSION['DJ_name']        =   $_POST['DJ_name'];
            $_SESSION['DJ_showname']    =   $_POST['DJ_showname'];
        }

Output:

Notice: Undefined variable: _SESSION in D:.....\main.php on line 19

Notice: Undefined variable: _SESSION in D:.....\main.php on line 21

NULL

pre_dump code:

    function pre_dump($var)
{
    echo '<pre>';
    var_dump($var);
    echo '</pre>';
}

4条回答
贪生不怕死
2楼-- · 2019-07-03 02:37

I found the error myself. Had an session_start() somewhere in my script that I didn't notice. Everything seems working now.

查看更多
神经病院院长
3楼-- · 2019-07-03 02:41

$_SESSION always exists no matter whether you run session_start() or not. So I think something else must be causing your error.

Could you post the code? It could be you have unset the variable somewhere (see this link).

查看更多
Fickle 薄情
4楼-- · 2019-07-03 02:47

Sounds to me like unset($_SESSION); was called.

查看更多
ゆ 、 Hurt°
5楼-- · 2019-07-03 02:53

I also encountered the same problem recently. I could not access the contents of the $_SESSION variable.

1) This was as a result of trying to access the $_SESSION variable before the declaration of session_start(); In my own case, I had already started a session in a header.php file. But I was accessing the $_SESSION variable before the include statement. Example;

<?php
 $username = $_SESSION['username'];
 //do some logical operation!!!
?> 
<?php include("header.php");?>

instead of doing something like this

<?php include("header.php");?>
<?php
 $username = $_SESSION['username'];
 //do some logical operation!!!
?> 

2) Another thing that may cause this problem, maybe a failure to start a session at the top of all the files that may require access to the $_SESSION variable using

session_start();

Hope this helps anybody that stumbles on the same problem. Although this is coming at a late hour.

查看更多
登录 后发表回答