Skip to content

Instantly share code, notes, and snippets.

@lfbittencourt
Created December 20, 2016 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lfbittencourt/994517d6cff9699217ffd884cb056e86 to your computer and use it in GitHub Desktop.
Save lfbittencourt/994517d6cff9699217ffd884cb056e86 to your computer and use it in GitHub Desktop.
An unserialize wrapper that gets rid of "Error at offset" errors.
<?php
/**
* This function fixes string lengths before unserializing a value,
* in case some content was found and replaced, for example.
*
* @param string $str
* @param array $options
* @return mixed
*/
function unserialize_after_fixing($str, array $options = [])
{
$str = preg_replace_callback('/s:(\d+):"(.*?)";/s', function ($matches) {
return 's:' . strlen($matches[2]) . ':"' . $matches[2] . '";';
}, $str);
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
return unserialize($str, $options);
}
return unserialize($str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment