Created
October 2, 2012 17:06
-
-
Save juzna/3821221 to your computer and use it in GitHub Desktop.
unserialize() with encoding conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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