当前位置: 动力学知识库 > 问答 > 编程问答 >

session - PHP - Losing $_SESSION variable index

问题描述:

I want to pass an array to another page, then use elements in that array to make JSON, and then echo it out for the first page to access it.

Right now I can send the array to the other page, I then format it how I want, I echo it out for the first page to get, but then when I try to echo fetch_get_contents of the url I'm echoing the info on, it all of a sudden breaks the $_SESSION variable.

This is in my first file

$_SESSION['map'] = $rowContentArray;

$url2 = "http:....php";

in my second file I can get the array fine and I do everything I want with it

I echo out the info I want from my other page, then when i try to access the info on the first page again, it breaks

just by adding this last line

$_SESSION['map'] = $rowContentArray;

$url2 = "http:.....php";

echo file_get_contents($url2, true);

I get the error that the index i'm using to access the array in the $_SESSION variable is undefined in my second file

$map = $_SESSION['map'];

error:

Notice: Undefined index: map

On the first file, I can echo out any random string after the session stuff and everything still works..but when i try to echo the url contents it breaks.

I am very confused as to what could be causing the session variable to be lost.

Thank you in advance for the help.

网友答案:

Mate, there is no any errors in your scripts! Actually this is exactly the expected behavior.

When you access the page from your browser a specific COOKIE is set and the $_SESSION array is bind to this cookie.

When you access the page with file_get_contents($url2, true); The server is assigning another COOKIEwith brand new $_SESSION array bind to it.

Obviously the second $_SESSION array do not have map key set, so as expected you are getting
Notice: Undefined index: map

Keep in mind that the variable $_SESSION is session specific, so if you have say 1000 simultaneously opened sessions to the server you have 1000 different versions of $_SESSION variable.

Check this article to get the things clearly: http://en.wikipedia.org/wiki/HTTP_cookie#Session_cookie

If you can define what is your specific use case we will be able to help you more.

The usual approach is to use GET or POST variables when you need to transfer data between different sessions. For example in your case you can try:
file_get_contents($url2 . '?map=' . json_encode($rowContentArray));

Then instead in the $_SESSION['map'] you will get your array in $_GET['map']

If the array $rowContentArray is big enough not to fit as a GET parameter, then you will have to use POST method.

分享给朋友:
您可能感兴趣的文章:
随机阅读: