PHP unserialize fails with non-encoded characters?

后端 未结 14 1772
遥遥无期
遥遥无期 2020-11-27 16:13
$ser = \'a:2:{i:0;s:5:\"héllö\";i:1;s:5:\"wörld\";}\'; // fails
$ser2 = \'a:2:{i:0;s:5:\"hello\";i:1;s:5:\"world\";}\'; // works
$out = unserialize($ser);
$out2 = un         


        
14条回答
  •  伪装坚强ぢ
    2020-11-27 16:35

    In my case the problem was with line endings (likely some editor have changed my file from DOS to Unix).

    I put together these apadtive wrappers:

    function unserialize_fetchError($original, &$unserialized, &$errorMsg) {
        $unserialized = @unserialize($original);
        $errorMsg = error_get_last()['message'];
        return ( $unserialized !== false || $original == 'b:0;' );  // "$original == serialize(false)" is a good serialization even if deserialization actually returns false
    }
    
    function unserialize_checkAllLineEndings($original, &$unserialized, &$errorMsg, &$lineEndings) {
        if ( unserialize_fetchError($original, $unserialized, $errorMsg) ) {
            $lineEndings = 'unchanged';
            return true;
        } elseif ( unserialize_fetchError(str_replace("\n", "\n\r", $original), $unserialized, $errorMsg) ) {
            $lineEndings = '\n to \n\r';
            return true;
        } elseif ( unserialize_fetchError(str_replace("\n\r", "\n", $original), $unserialized, $errorMsg) ) {
            $lineEndings = '\n\r to \n';
            return true;
        } elseif ( unserialize_fetchError(str_replace("\r\n", "\n", $original), $unserialized, $errorMsg) ) {
            $lineEndings = '\r\n to \n';
            return true;
        } //else
        return false;
    }
    

提交回复
热议问题