How can I convert an array to a serialized string that I can write to a session file? This is being done in a command line script, not in a browser, so I can not use session_write_close()
.
I have tried serialize()
function and that does not convert it properly (see below).
Notice: I already know I shouldn't manually write to a session file, and I should use the database for session data instead.
If I use file_get_contents()
on the session file I get:
user_id|i:4;user_first_name|s:9:"FirstName";user_last_name|s:8:"LastName";user_last_login|s:10:"2016-06-03";random_data|a:4:{s:2:"ID";i:83;s:3:"URL";a:1:{i:0;s:23:"https://www.example.com";}s:4:"Date";s:10:"2016-06-08";s:4:"Year";s:4:"2016";}
I convert it to an array with some PHP and get:
Array
(
[user_id] => 1
[user_first_name] => FirstName
[user_last_name] => LastName
[user_last_login] => 2016-06-03
[random_data] => Array
(
[ID] => 83
[URL] => Array
(
[0] => https://www.example.com
)
[Date] => 2016-06-08
[Year] => 2016
)
)
Now I need to convert the array back into a string for the session file:
user_id|i:4;user_first_name|s:9:"FirstName";user_last_name|s:8:"LastName";user_last_login|s:10:"2016-06-03";random_data|a:4:{s:2:"ID";i:83;s:3:"URL";a:1:{i:0;s:23:"https://www.example.com";}s:4:"Date";s:10:"2016-06-08";s:4:"Year";s:4:"2016";}
I used Serialize() and got this (not the same as what came out of the session file):
a:12:{s:7:"user_id";i:4;s:15:"user_first_name";s:9:"FirstName";s:14:"user_last_name";s:8:"LastName";s:15:"user_last_login";s:10:"2016-06-03";s:11:"random_data";a:24:{s:2:"ID";i:83;s:3:"URL";a:1:{i:0;s:23:"https://www.example.com";}s:3:"API";N;s:4:"Date";s:10:"2016-06-08";s:4:"Year";s:4:"2016";}}
EDIT: It has to be the same format as the original string format (from file_get_contents()
) because when I insert the serialize()
string format it logs me out of the website.