$_SESSION

$HTTP_SESSION_VARS [已弃用]

$_SESSION -- $HTTP_SESSION_VARS [已弃用]Session 变量

说明

当前脚本可用 SESSION 变量的数组。更多关于如何使用的信息,参见 Session 函数 文档。

$HTTP_SESSION_VARS 包含相同的信息,但它不是一个超全局变量。 (注意 $HTTP_SESSION_VARS$_SESSION 是不同的变量,PHP 处理它们的方式不同)

更新日志

版本 说明
4.1.0 引入 $_SESSION,弃用 $HTTP_SESSION_VARS

注释

Note:

"Superglobal"也称为自动化的全局变量。这就表示其在脚本的所有作用域中都是可用的。不需要在函数或方法中用 global $variable; 来访问它。

参见

User Contributed Notes

ms at meilenstein dot ms 25-Jan-2019 11:56
I would be wary to use PHP Sessions for application-critical tasks. So far, I have had very troubling experiences with random loss of session data, as described in these bug reports:

https://bugs.php.net/bug.php?id=19022
https://bugs.php.net/bug.php?id=19029
https://bugs.php.net/bug.php?id=70584
dbagnara 22-Nov-2017 06:27
The key of values added to $_SESSION must not be numeric. An error message will be generated and the session will not be saved.

"Notice: Unknown: Skipping numeric key 1511374723 in Unknown on line 0"
ignasitort at gmail dot com 25-Apr-2017 08:07
I have a weird problem, when using $_SESSION  to store  a nonce. My nonces never match.
Maybe the PHP code is called twice (maybe is WP or maybe is the BROWSER) but Html is rendered with the first NONCE value, but as random nonce  are created twice, returning PHP function (called by Javascript AJAX ) checks for the second value. As far , as I can not solve
My solution is:  always check first if the NONCE exist before creating a new random value for the nonce. This way nonce cannot  change if PHP called twice.

<?PHP

 
if (isset($_SESSION['nonce']) && !empty($_SESSION['nonce'])){
       
error_log("NONCE_ NOT EMPTY");
        }
    else
       
$_SESSION['nonce'] =  function_rand_str(32);

?>
Nitin Sharma 02-Jan-2017 10:42
This is the code for session.php but it is not working properly. I have three field in my database log_id,user_email,user_pass. and when I want to login into my website it does not works. I've some issues with session creation.
if you could help me please go ahed.
<?php
    $dbhost    
= "localhost";
   
$dbname     = "new";
   
$dbuser     = "root";
   
$dbpass     = "";

   
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);

   
session_start();
   
$user_check=$_SESSION['login_user'];
   
$result = $conn->prepare("SELECT * FROM login WHERE user_email = :user_check");                                             
   
$result->execute(array(":usercheck"=>$user_check));

   
$row = $result->fetch(PDO::FETCH_ASSOC);

   
$login_session =$row['user_email'];
   
$user_id =$row['log_id'];
   
$user_passwords = $row['user_pass'];

    if(!isset(
$login_session))
        {
           
$conn = null;
           
header('Location: www.fb.com');
        }
?>
buckmanhands at gmail dot com 20-Sep-2016 10:56
If you are using a session variable as a token to use as a handshake on next page load and the token updates on the new page load, but they mysteriously will not match and there is no obvious explanation. I had the following happen and maybe it will save you some time.

I was making a form that allowed an image upload and had an image tag ready to drop the src of the preview in after the file was chosen. But I had a preset src of "#"... this loaded the page a second time in the background and updated my token invisibly causing a broken handshake.

My tag looked like this:

<img src="#" id="myimagepreview" alt="image preview" />

Leave the source blank and the handshake will not break.
Tugrul 09-Mar-2015 05:04
Creating New Session
==========================
<?php
session_start
();
/*session is started if you don't write this line can't use $_Session  global variable*/
$_SESSION["newsession"]=$value;
?>
Getting Session
==========================
<?php
session_start
();
/*session is started if you don't write this line can't use $_Session  global variable*/
$_SESSION["newsession"]=$value;
/*session created*/
echo $_SESSION["newsession"];
/*session was getting*/
?>
Updating Session
==========================
<?php
session_start
();
/*session is started if you don't write this line can't use $_Session  global variable*/
$_SESSION["newsession"]=$value;
/*it is my new session*/
$_SESSION["newsession"]=$updatedvalue;
/*session updated*/
?>
Deleting Session
==========================
<?php
session_start
();
/*session is started if you don't write this line can't use $_Session  global variable*/
$_SESSION["newsession"]=$value;
unset(
$_SESSION["newsession"]);
/*session deleted. if you try using this you've got an error*/
?>

Reference: http://gencbilgin.net/php-session-kullanimi.html
Fred 07-Sep-2013 03:09
Regarding array keys, from http://php.net/manual/en/language.types.array.php, "Strings containing valid integers will be cast to the integer type".

The manual on $_SESSION says "An associative array". So an associative array is expected literally...? It does no one any good if this bit of important info about accessing and storing session data remains buried in manual comments.

Session variables with a single number will not work, however "1a" will work, as will "a1" and even a just single letter, for example "a" will also work.

(Invalid)
1st page

<?php
session_start
();
$_SESSION["1"] = "LOGGED";
?>

2nd page

<?php
session_start
();
echo
$_SESSION["1"];
?>

---------------------------------------------------------------

(Valid)
1st page

<?php
session_start
();
$_SESSION["a"] = "LOGGED";
?>

2nd page

<?php
session_start
();
echo
$_SESSION["a"];
?>

---------------------------------------------------------------

(Valid)
1st page

<?php
session_start
();
$_SESSION["a1"] = "LOGGED";
?>

2nd page

<?php
session_start
();
echo
$_SESSION["a1"];
?>

---------------------------------------------------------------

Example from PHP.net manual on Session variables

<?php
$_SESSION
[1][1] = 'cake'; // fails

$_SESSION['v1'][2] = 'cake'; // works
?>

Source: http://php.net/manual/en/language.types.array.php
opajaap at opajaap dot nl 31-Aug-2013 11:51
Be carefull with $_SESSION array elements when you have the same name as a normal global.

The following example leads to unpredictable behaviour of the $wppa array elements, some are updated by normal code, some not, it is totally unpredictable what happens.

<?php
global $wppa;
$wppa = array( 'elm1' => 'value1', 'elm2' => 'value2', ....etc...);

if ( !
session_id() ) @ session_start();
if ( ! isset(
$_SESSION['wppa']) $_SESSION['wppa'] = array();

if ( ! isset(
$_SESSION['wppa']['album']) ) $_SESSION['wppa']['album'] = array();
$_SESSION['wppa']['album'][1234] = 1;

$wppa['elm1'] = 'newvalue1';

print_r($_SESSION);
?>
This will most likely display Array ( [wppa] => Array ( [album] => Array ( [1234] => 1 ) [elm1] => 'newvalue1' [elm2] => 'value2' ... etc ...
But setting $wppa['elm1'] to another value or referring to it gives unpredictable results, maybe 'value1', or 'newvalue1'.

The most strange behaviour is that not all elements of $wppa[xx] show up as $_SESSION['wppa'][xx].
Miller 12-Aug-2013 08:48
I wrote a little page for controlling/manipulating the session. Obviously, never use this on a production server, but I use it on my localhost to assist me in checking and changing session values on the fly.

Again, it makes use of eval() and exposes the session, so never use this on a web server.

<?php
error_reporting
(E_ALL);
session_start();
if (isset(
$_POST['session'])) {
   
$session = eval("return {$_POST['session']};");
    if (
is_array($session)) {
       
$_SESSION = $session;
       
header("Location: {$_SERVER['PHP_SELF']}?saved");
    }
    else {
       
header("Location: {$_SERVER['PHP_SELF']}?error");
    }
}

$session = htmlentities(var_export($_SESSION, true));
?>
<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta charset="UTF-8">
        <title>Session Variable Management</title>
        <style>
            textarea { font: 12px Consolas, Monaco, monospace; padding: 2px; border: 1px solid #444444; width: 99%; }
            .saved, .error { border: 1px solid #509151; background: #DDF0DD; padding: 2px; }
            .error { border-color: #915050; background: #F0DDDD; }
        </style>
    </head>
    <body>
        <h1>Session Variable Management</h1>
<?php if (isset($_GET['saved'])) { ?>
        <p class="saved">The session was saved successfully.</p>
<?php } else if (isset($_GET['error'])) { ?>
        <p class="error">The session variable did not parse correctly.</p>
<?php } ?>
        <form method="post">
            <textarea name="session" rows="<?php echo count(preg_split("/\n|\r/", $session)); ?>"><?php echo $session; ?></textarea>
            <input type="submit" value="Update Session">
        </form>
    </body>
</html>
pike-php at kw dot nl 07-Feb-2011 06:00
When accidently assigning a unset variable to $_SESSION, like

   $_SESSION['foo'] = $bar

while $bar was not defined, I got the following error message:

"Warning: Unknown(): Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. "

The errormessage was quite unrelated and got me off-track. The real error was, $bar was not defined.
Dave 17-Nov-2009 02:05
If you deploy php code and cannot control whether register_globals is off, place this snippet in your code to prevent session injections:

<?php
if (isset($_REQUEST['_SESSION'])) die("Get lost Muppet!");
?>
charlese at cvs dot com dot au 04-Jul-2009 06:47
I was having troubles with session variables working in some environments and being seriously flaky in others. I was using $_SESSION as an array. It works properly when I used $_SESSION as pointers to arrays. As an example the following code works in some environments and not others.

<?php
//Trouble if I treate $form_convert and $_SESSION['form_convert'] as unrelated items
$form_convert=array();
if (isset(
$_SESSION['form_convert'])){
       
$form_convert=$_SESSION['form_convert'];
    }
}
?>
The following works well.
<?php
if (isset($_SESSION['form_convert'])){
   
$form_convert = $_SESSION['form_convert'];
}else{
   
$form_convert = array();
   
$_SESSION['form_convert']=$form_convert;
}
?>
bohwaz 31-Aug-2008 02:43
Please note that if you have register_globals to On, global variables associated to $_SESSION variables are references, so this may lead to some weird situations.

<?php

session_start
();

$_SESSION['test'] = 42;
$test = 43;
echo
$_SESSION['test'];

?>

Load the page, OK it displays 42, reload the page... it displays 43.

The solution is to do this after each time you do a session_start() :

<?php

if (ini_get('register_globals'))
{
    foreach (
$_SESSION as $key=>$value)
    {
        if (isset(
$GLOBALS[$key]))
            unset(
$GLOBALS[$key]);
    }
}

?>
Steve Clay 17-Aug-2008 06:28
Unlike a real PHP array, $_SESSION keys at the root level must be valid variable names.

<?php
$_SESSION
[1][1] = 'cake'; // fails

$_SESSION['v1'][1] = 'cake'; // works
?>

I imagine this is an internal limitation having to do with the legacy function session_register(), where the registered global var must similarly have a valid name.
jherry at netcourrier dot com 01-Aug-2008 04:16
You may have trouble if you use '|' in the key:

$_SESSION["foo|bar"] = "fuzzy";

This does not work for me. I think it's because the serialisation of session object is using this char so the server reset your session when it cannot read it.

To make it work I replaced '|' by '_'.