msgbartop
I will happily conduct a FREE basic web security scan for any genuine organization interested in my services to point out whether or not I can find vulnerabilities in your application. Just contact me.
Need a PHP Programmer, PHP staff or project manager? Contact me now.
msgbarbottom

18 Nov 09 PHP Developer – Serialize

PHP has two ver useful functions, serialize and unserialize.

serialize() generates a string based storable representation of any variable type that you like. Take a complex variable:

<?php
a = "test";
$obj->b = "string";
$obj->c = Array("this", "is", "a", "test", "array");
$obj->d = new stdClass();
$obj->d->var1 = "some text";
$obj->d->var2 = Array("this", "is", "another", "array");

print_r($obj);
?>

wwwtest:~# php ./test.php
stdClass Object
(
    [a] => test
    [b] => string
    [c] => Array
        (
            [0] => this
            [1] => is
            [2] => a
            [3] => test
            [4] => array
        )

    [d] => stdClass Object
        (
            [var1] => some text
            [var2] => Array
                (
                    [0] => this
                    [1] => is
                    [2] => another
                    [3] => array
                )

        )

)

Now, changing the last line of the script to:

$mystring = serialize($obj);
echo "Serialized data is: " . $mystring;

We now get:

Serialized data is: O:8:"stdClass":4:{s:1:"a";s:4:"test";s:1:"b";s:6:"string";s:1:"c";a:5:{i:0;s:4:"this";i:1;s:2:"is";i:2;s:1:"a";i:3;s:4:"test";i:4;s:5:"array";}s:1:"d";O:8:"stdClass":2:{s:4:"var1";s:9:"some text";s:4:"var2";a:4:{i:0;s:4:"this";i:1;s:2:"is";i:2;s:7:"another";i:3;s:5:"array";}}}

We can just as easily return this to it’s original form with unserialize(). This is useful because this flat string can be stored in a database or perhaps even passed through a site and associated with the current user for his usage preferences.

Tags: , , , ,



Leave a Comment

You must be logged in to post a comment.