PHP反序列化序列化数据

时间:2014-09-24 10:07:24

标签: php wordpress serialization

我在序列化数据的反序列化时遇到问题。

数据被序列化并保存在数据库中。

此数据包含我想要回馈给fgetcsv的上传的.csv网址。

fgetcsv需要一个数组,现在给出了一个字符串,所以我需要反序列化数据,但这会给我带来错误。

我在网上http://davidwalsh.name/php-serialize-unserialize-issues找到了这个,但这似乎不起作用。所以我希望有人能告诉我哪里出错了:

这是错误:

Notice: unserialize() [function.unserialize]: Error at offset 0 of 1 bytes in /xxx/public_html/multi-csv-upload.php on line 163

我发现这意味着序列化数据中有某些字符会导致文件在反序列化后损坏(",',:,;)

第163行:

jj_readcsv(unserialize ($value[0]),true);` // this reads the url of the uploaded csv and tries to open it.

以下是使数据序列化的代码:

update_post_meta($post_id, 'mcu_csv', serialize($mcu_csv));

这是WordPress

以下是输出:

echo '<pre>';
print_r(unserialize($value));
echo '</pre>';

Array ( [0] => http://www.domain.country/xxx/uploads/2014/09/test5.csv )

我看到它的方式不应该在这里出错。

任何人都有一些想法,我可以如何反序列化,以便我可以使用它? 这就是我做的事情......

public function render_meta_box_content($post)
{

    // Add an nonce field so we can check for it later.
    wp_nonce_field('mcu_inner_custom_box', 'mcu_inner_custom_box_nonce');

    // Use get_post_meta to retrieve an existing value from the database.
    $value = get_post_meta($post->ID, 'mcu_images', true);

    echo '<pre>';
        print_r(unserialize($value));
    echo '</pre>';

    ob_start();
    jj_readcsv(unserialize ($value[0]),true);
    $link = ob_get_contents();
    ob_end_clean();
    $editor_id = 'my_uploaded_csv';

    wp_editor( $link, $editor_id );




    $metabox_content = '<div id="mcu_images"></div><input type="button" onClick="addRow()" value="Voeg CSV toe" class="button" />';
    echo $metabox_content;

    $images = unserialize($value);

    $script = "<script>
        itemsCount= 0;";
    if (!empty($images))
    {
        foreach ($images as $image)
        {
            $script.="addRow('{$image}');";
        }
    }
    $script .="</script>";
    echo $script;
}

function enqueue_scripts($hook)
{
    if ('post.php' != $hook && 'post-edit.php' != $hook && 'post-new.php' != $hook)
        return;
    wp_enqueue_script('mcu_script', plugin_dir_url(__FILE__) . 'mcu_script.js', array('jquery'));
}

1 个答案:

答案 0 :(得分:1)

您正在尝试访问序列化字符串的第一个元素:

jj_readcsv(unserialize ($value[0]),true);

由于字符串本质上是字符数组,因此您尝试反序列化序列化字符串的第一个字符。

您需要取消序列化1st然后访问数组元素:

//php 5.4+
jj_readcsv(unserialize ($value)[0],true);
//php < 5.4

$unserialized = unserialize ($value);
jj_readcsv($unserialized[0],true);

或者,如果只有一个元素,不要在第一个位置存储数组,只需保存url字符串,不需要序列化:

//save
update_post_meta($post_id, 'mcu_csv', $mcu_csv[0]);
//access
jj_readcsv($value, true);