👿先奉劝大家,不懂数据和代码的情况下就不要瞎JB改,改坏了自己又处理不了。然后又是我的事,帮你吧,我真的很忙,时间成本太高,不帮你吧,看你自己又解决不了,又不忍心看着你干着急......

🙄今天有个用户在数据库里面修改了序列化数据,导致序列化数据损坏,网站部分设置数据丢失。🤕这种情况我也是第一次遇到,本来就非常忙,帮个忙又白白浪费了几个小时!

他在修改序列化数据前备份了序列化数据,但是不知道怎么回事,重新保存序列化数据后会被截断,unserialize也没有用,折腾了半天最后总算是搞好了。

将下面的代码添加到当前使用的WordPress主题的functions.php中。

function dahuzi_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 dahuzi_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+):"(.*)%', 'dahuzi_fix_str_length', $line);
    }
    return $new_data;
}

按下面的方式进行调试

//将序列化存储在一个txt文件中,放在主题根目录
$corruptedSerialization = file_get_contents(get_template_directory_uri().'/test.txt');

//尝试取消对原始字符串的序列化
$unSerialized = unserialize($corruptedSerialization);

//万一发生故障,我们试着修理一下
if(!$unSerialized){
    $repairedSerialization = dahuzi_fix_serialized($corruptedSerialization);
    $unSerialized = unserialize($repairedSerialization);
}
//如果你需要打印数据请使用下面的代码
var_dump($unSerialized);
//使用serialize函数将其序列化,然后手动复制序列化数据保存回数据库。
serialize($unSerialized);