Skip to content

Instantly share code, notes, and snippets.

@755
Created October 22, 2012 09:55
Show Gist options
  • Save 755/3930711 to your computer and use it in GitHub Desktop.
Save 755/3930711 to your computer and use it in GitHub Desktop.
Change codeigniter session to work with JSON
<?php
class MY_Session extends CI_Session {
/**
* Serialize an array
*
* This function first converts any slashes found in the array to a temporary
* marker, so when it gets unserialized the slashes will be preserved
*
* @access private
* @param array
* @return string
*/
function _serialize($data)
{
if (is_array($data))
{
foreach ($data as $key => $val)
{
if (is_string($val))
{
$data[$key] = str_replace('\\', '{{slash}}', $val);
}
}
}
else
{
if (is_string($data))
{
$data = str_replace('\\', '{{slash}}', $data);
}
}
return json_encode($data);
}
// --------------------------------------------------------------------
/**
* Unserialize
*
* This function unserializes a data string, then converts any
* temporary slash markers back to actual slashes
*
* @access private
* @param array
* @return string
*/
function _unserialize($data)
{
$data = @json_decode($data,TRUE);
if (is_array($data))
{
foreach ($data as $key => $val)
{
if (is_string($val))
{
$data[$key] = str_replace('{{slash}}', '\\', $val);
}
}
return $data;
}
return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data;
}
}
@twosg
Copy link

twosg commented Feb 9, 2016

This solved my character encoding problem with ISO and UTF-8 data 👍 Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment