Skip to content

Instantly share code, notes, and snippets.

@juzna
Created October 2, 2012 17:06
Show Gist options
  • Save juzna/3821221 to your computer and use it in GitHub Desktop.
Save juzna/3821221 to your computer and use it in GitHub Desktop.
unserialize() with encoding conversion
<?php
/**
* Hacked unserialize: works when encoding changed after serialization
* Problem: serialize cp1250, convert to utf8, unserialize. Length in bytes is bigger now!
*
* Also, it throws when something else is wrong
*
* @param string $s
* @return mixed
*
* @throws ErrorException
*/
function unserialize2($s) {
$offsetError = FALSE;
set_error_handler(function($severity, $message, $file, $line) use (&$offsetError) {
if ($offsetError === FALSE && preg_match('~Error at offset \d+ of \d+ bytes~', $message)) $offsetError = TRUE;
else {
restore_error_handler();
throw new \ErrorException($message, 0, $severity, $file, $line);
}
});
// try normal
$ret = unserialize($s);
// recode
if ($offsetError) {
$s = preg_replace_callback(
'!(?<=^|;)s:(\d+)(?=:"(.*?)";(?:}|a:|s:|b:|d:|i:|o:|N;))!s',
'_serialize_fix_callback',
$s
);
$ret = unserialize($s);
}
restore_error_handler();
return $ret;
}
// used in previous function
function _serialize_fix_callback($match) {
return 's:' . strlen($match[2]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment