简体   繁体   中英

PHP session won't show all keys after AJAX call

So I came across something before that didn't behave as I expected and I couldn't figure out the reason. I had a PHP session variable similar to the following:

{
    [quiz_id] => 1,

    [1] => {object1},
    [2] => {object2},
    [3] => {object3}
}

I had an AJAX call going to a page which was simply calling print_r() on the session variable and returning it. The thing is, the return array only consisted of the quiz_id key and none of the other fields. The page which made the AJAX request also called print_r() on the session before the AJAX call and it printed out as expected.

I changed the name of the numbered keys and everything worked as expected after that. Is there some nuance of sessions or AJAX that I missed somewhere? I can't imagine why only the one key would be available in the session.

Its not about the ajax request. Try to reproduce it by making a page that prints the session, then sets the session. Probably when you reload the page the numeric key/value pair will never be there on the print.

Php default session handler internally does not use serialize() to store the data. The method it uses can not store numeric keys, or keys that have "|" or "!" characters in them (in fact having "|" in a key will produce a completly empty session). This may change with later PHP versions, but its like this in 5.4 .

You can use a custom session handler to use numeric keys too.
See here for general info: http://php.net/manual/en/session.customhandler.php
And here is the core part of it: http://php.net/manual/en/function.session-set-save-handler.php (simply speaking, the read() and write() functions are getting the serialized/unserialized $_SESSION array).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM