Skip to content

Instantly share code, notes, and snippets.

@chlp
Created May 7, 2019 14:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chlp/8dac656c562941308d4621fd61856e22 to your computer and use it in GitHub Desktop.
Save chlp/8dac656c562941308d4621fd61856e22 to your computer and use it in GitHub Desktop.
php change str_replace inside serialized data and fix it
<?php
$change_from = 'old_string';
$change_to = 'new_string_new_length';
$serialized = file_get_contents('serialized_data.txt');
$serialized = str_replace($change_from, $change_to, $serialized);
function fix_str_length($matches) {
$string = $matches[2];
$right_length = strlen($string); // yes, strlen even for UTF-8 characters, PHP wants the mem size, not the char count
return 's:' . $right_length . ':"' . $string . '";';
}
function fix_serialized($string) {
// securities
if ( !preg_match('/^[aOs]:/', $string) ) return $string;
if ( @unserialize($string) !== false ) return $string;
$string = preg_replace("%\n%", "", $string);
// doublequote exploding
$data = preg_replace('%";%', "µµµ", $string);
$tab = explode("µµµ", $data);
$new_data = '';
foreach ($tab as $line) {
$new_data .= preg_replace_callback('%\bs:(\d+):"(.*)%', 'fix_str_length', $line);
}
return $new_data;
}
$serialized = fix_serialized($serialized);
echo $serialized;
@tbutterf
Copy link

This is great!

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