serialize

Description

This is useful for storing or passing PHP values around without
losing their type and structure.

To make the serialized string into a PHP value again, use
unserialize().

Parameters

value

The value to be serialized. serialize()
handles all types, except the resource-type and some objects (see note below).
You can even serialize() arrays that contain
references to itself. Circular references inside the array/object you
are serializing will also be stored. Any other
reference will be lost.

When serializing objects, PHP will attempt to call the member function
__sleep() prior to serialization.
This is to allow the object to do any last minute clean-up, etc. prior
to being serialized. Likewise, when the object is restored using
unserialize() the __wakeup() member function is called.

Note:

Object's private members have the class name prepended to the member
name; protected members have a '*' prepended to the member name.
These prepended values have null bytes on either side.

Return Values

Returns a string containing a byte-stream representation of
value that can be stored anywhere.

Note that this is a binary string which may include null bytes, and needs
to be stored and handled as such. For example,
serialize() output should generally be stored in a BLOB
field in a database, rather than a CHAR or TEXT field.

Examples

Example #1 serialize() example

<?php// $session_data contains a multi-dimensional array with session// information for the current user. We use serialize() to store// it in a database at the end of the request.

Notes

Note:

Note that many built-in PHP objects cannot be serialized. However, those with
this ability either implement the Serializable interface or the
magic __sleep() and
__wakeup() methods. If an
internal class does not fulfill any of those requirements, it cannot reliably be
serialized.

There are some historical exceptions to the above rule, where some internal objects
could be serialized without implementing the interface or exposing the methods. Notably,
the ArrayObject prior to PHP 5.2.0.

Warning

When serialize() serializes objects, the leading backslash is not included in the class name of namespaced classes for maximum compatibility.

String values are always in double quotes Array keys are always integers or strings "null => 'value'" equates to 's:0:"";s:5:"value";', "true => 'value'" equates to 'i:1;s:5:"value";', "false => 'value'" equates to 'i:0;s:5:"value";', "array(whatever the contents) => 'value'" equates to an "illegal offset type" warning because you can't use an array as a key; however, if you use a variable containing an array as a key, it will equate to 's:5:"Array";s:5:"value";', and attempting to use an object as a key will result in the same behavior as using an array will.*/?>

Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.

I've encountered this too many times in my career, it makes for difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.

That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.

If you are going to serialie an object which contains references to other objects you want to serialize some time later, these references will be lost when the object is unserialized.The references can only be kept if all of your objects are serialized at once.That means:

The basic serialization looks good although, in its current form, it works on the basis of generating Javascript source which a browser executes as a page loads. Using Javascripts eval() the same can be done with strings containing Javascript if youre working with something like XMLHTTPRequest

In my specific situation, I wanted to be able to pass some data from page to page, but without relying on a session variable. The answer I came up with was to serialize() the object in question, pass it on to the next page as a hidden form field, then unserialize() it. When ALL class variables are public, this worked fine. However, if there was at least one private/protected variable, the code no longer worked as expected ("Fatal error: Call to a member function display() on a non-object in page2.php on line 4")

As others have already mentioned, private/protected class variables will not behave nicely (private variables are prefixed by class_name + &#65533;, while protected variables are only prefixed by &#65533; - when looking at the page source using Firefox). Internet Explorer does NOT display the extra character between the class name and variable name, but the code still doesn't work as one would expect.

If you are serializing an object to store it in the database, using __sleep() can save you some space. The following code will not store empty (null) variables in the serialized string. For my purposes this saved a lot of space, since some of the member variables would not be given values.

I have also written some code for importing serialized PHP data into PERL and then writing it back into PHP. I think the similar library posted above is actually more robust for a few select cases, but mine is more compact and a little easier to follow. I'd really like comments if anyone finds this useful or has improvements. Please credit me if you use my code.

If serializing objects to be stored into a postgresql database, the 'null byte' injected for private and protected members throws a wrench into the system. Even pg_escape_bytea() on the value, and storing the value as a binary type fails under certain circumstances.

The only gotcha's with this method is if your object member names or values may somehow contain the odd "~~NULL_BYTE~~" string. If that is the case, then str_replace() to a string that you are guaranteed not to have any where else in the string that serialize() returns.
Also remember to define the class before calling unserialize().

If you are storing session data into a postgresql database, then this workaround is an absolute must, because the $data passed to the session's write function is already serialized.

Here's a serialization function that doesn't serialize objects (it could, I just didn't care for that) but writes straight to a file. Very useful if you run out of memory when trying to serialize that 5-level nested 100000-entry array of strings.

I did the same test as MiChAeLoKGB but in another version of PHP.I don't post his code because I executed exactly the same script (after correcting a small variable naming error and add a line to display the PHP version).

I was trying to submit a serialized array through a hidden form field using POST and was having a lot of trouble with the quotes. I couldn't figure out a way to escape the quotes in the string so that they'd show up right inside the form, so only the characters up to the first set of quotes were being sent.

My solution was to base64_encode() the string, put that in the hidden form field, and send that through the POST method. Then I decoded it (using base64_decode()) on the other end. This seemed to solve the problem.

I needed to serialize an array to store it inside a database.I was looking for a fast, simple way to do serialization, and I came out with 2 options: serialize() or json_encode().

I ran some benchmarks to see which is the faster, and, surprisingly, I found that serialize() is always between 46% and 96% SLOWER than json_encode().So, if you don't need to serialize objects and have the json extension available, consider using it instead of serialize().

NOTE: php's serialize does not properly serialize arrays with which a slice of the array is a reference to the array itself, observe:

<?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:

When using serialize() to convert, say, an array to a string to pass via HTML forms, you will likely run into issues with quoting. This is because serialize() puts values in double quotes. The simplest solution is to quote your HTML form value with single quotes rather than double quotes. (This *is* allowed, according to W3C specs.)