CodeIgniter Forums

Full Version: Sessions _serialize not working recursively
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Unknown[/eluser]
Hey guys !

I was banging my head into the wall this morning because i couldn't figure out what was the problem.

I have a huge session array (i know, it's bad but I REALLY can't do anything else) with some arrays in it.

This is a dumbed down version of what I have :

Code:
$user = array('name' => 'name',
              'downloads' => array('url' => 'http://www.perdu.com', 'name' => 'something\with\blackslashes')
         );

The problem was that when serializing the array, the part with the \es wasn't processed and thus causing the _unserialize method to crash. Of course i do addslashes to my datas.

So i changed the code a little to add some recusivity in it :

Code:
function _serialize($data)
{
  if (is_array($data))
  {
  
   //EDITED PART
   array_walk_recursive($data, function(&$item,$key){
    if (is_string($item))
    {
     $item = str_replace('\\', '{{slash}}', $item);
    }
   });
  }
  else
  {
   if (is_string($data))
   {
    $data = str_replace('\\', '{{slash}}', $data);
   }
  }

  return serialize($data);
}

Now everything is working correctly.

Going through all the session process (database, serialize, unserialze, test for special characters...) was a real pain.

El Forum

[eluser]erikig[/eluser]
Thanks for this, it fixed a lot of the persistent session issues that I've been running into.

If anyone has been running into problems saving arrays of data this helps resolve the issue.

I'd recommend using a MY_Session.php library instead of modifying the core CodeIgniter code. A corresponding update is also needed to the _unserialize function.

I had opened an issue on GitHub and I submitted this as a solution:
https://github.com/EllisLab/CodeIgniter/issues/1562

This allows CI_Session to work a lot more like the Native PHP sessions.

Regards,
E

El Forum

[eluser]aamche[/eluser]
No recursion. It appears this is still the case years later. Thanks for this.