开发者

a stupid 'important' question about php $_SESSION array

开发者 https://www.devze.com 2023-02-07 06:57 出处:网络
I have 2 files that put something in the $_SESSION array. file1.php <?php session_start(); $_SESSION[] = \'Hi\';

I have 2 files that put something in the $_SESSION array. file1.php

<?php
session_start();

$_SESSION[] = 'Hi';

echo '<pre>';
print_r($_SESSION);
echo '</pre>';

That prints

Array
(
    [0] => Hi
)

And file2.php that is similar to file1

<?php
session_start();

$_SESSION[] = 'There!';

echo '<pre>';
print_r($_SESSION);
echo '</pre>';

I suppose to go to file1 at first and then move to file2. Printing $_SESSION in file2 should output

Array
(
    [0] => Hi
    [1] => There!
)

am I wrong?

I've to mention that I get the notice: Unknown skipping numeric key 0 in Unknown on line 0. And the register_globals in my php.ini is set to Off.

As I see in the comments for someone of you file2 prints an array of 2 items and for someon开发者_如何转开发e else (like me) the 'hi' items get lost. This seems to happen, but not for Marc B, only if we use a number as index of the session array, not with a string.

For Marc B the session behaves as I expected. Can you post your php.ini here? So I can compare yours with mine?


Superglobals like $_SESSION are not normal arrays. You should store an array inside $_SESSION, like so:

file 1: $_SESSION['foo'][] = 'Hi!';

file 2: $_SESSION['foo'][] = 'there';


You aren't giving $_SESSION the appropriate key.


No, that should work. In fact, if you just kept reloading file1, you'd just get a series of "Hi", "Hi", "Hi", etc.. array entries.


Is there a particular reason why you did

$_SESSION[]='Hi' instead of $_SESSION["Greet"]='Hi'?

I have tested your code. when i started file1.php i have the following:

Array
(
    [0] => hi
)

with the following notice: Unknown skipping numeric key 0 in Unknown on line 0 and after that i went on to file2.php i have the following:

Array
(
    [0] => there!
)

with the same notice. simply put to answer your question you are wrong :). If you added the indexes ("greet" and "meet" respectively) to the session variable this would be the output on page 1:

Array
(
   [greet]=> hi      
)

and when you go on file2.php you would have:

Array
(
  [greet] => hi
  [meet] => there!
)


file1:

<?php
session_start();

$_SESSION['0'] = 'Hi';

echo '<pre>';
print_r($_SESSION);
echo '</pre>';

That prints 
Array
(
    [0] => Hi
)

And file2.php that is similar to file1 but different session index

<?php
session_start();

$_SESSION['1'] = 'There!';

echo '<pre>';
print_r($_SESSION);
echo '</pre>';

Now this prints 
Array
(
    [0] => Hi
    [1] => There!
)
0

精彩评论

暂无评论...
验证码 换一张
取 消