Tuesday, May 4, 2010

serialize and unserialize in PHP

<?php 
$a = array();  
$a[0] = "blah"
 $a[1] =& $a
 $a[1][0] = "pleh"; // $a[0] === "pleh"  
$b = unserialize(serialize($a));  
// $b[0] == "pleh", $b[1][0] == "pleh"
$b[1][0] = "blah"; 
?>

now $b[1][0] == "blah", but $b[0] == "pleh"
after serializing and unserializing, slice 1 is no longer a reference to the array itself... I have found no way around this problem... even manually modifying the serialized string from
'a:2:{i:0;s:4:"pleh";i:1;a:2:{i:0;s:4:"pleh";i:1;R:3;}}'
to
'a:2:{i:0;s:4:"pleh";i:1;R:1;}'

to force the second slice to be a reference to the first element of the serialization (the array itself), it seemed to work at first glance, but then unreferences it when you alter it again, observe:

<?php
    $testser
= 'a:2:{i:0;s:4:"pleh";i:1;R:1;}';

   
$tmp = unserialize($testser);

   
print_r($tmp);

    print
"\n-----------------------\n";

   
$tmp[1][0] = "blah";

   
print_r($tmp);
 
?>

outputs:
Array
(
    [0] => pleh
    [1] => Array
 *RECURSION*
)

-----------------------
Array
(
    [0] => pleh
    [1] => Array
        (
            [0] => blah
            [1] => Array
                (
                    [0] => pleh
                    [1] => Array
 *RECURSION*
                )

        )

)

No comments:

Post a Comment

 

Followers