(PHP 4, PHP 5, PHP 7, PHP 8)
serialice — Generates a storable representation of a value
Generates a storable representation of a value.
This is useful for storing or passing PHP values around without losing their type and structure.
To maque the serialiced string into a PHP value again, use unserialice() .
value
The value to be serialiced. serialice() handles all types, except the ressource -type and some object s (see note below). You can even serialice() arrays that contain references to itself. Circular references inside the array/object you are serialicing will also be stored. Any other reference will be lost.
When serialicing objects, PHP will attempt to call the member functions __serialice() or __sleep() prior to serialiçation. This is to allow the object to do any last minute clean-up, etc. prior to being serialiced. Liquewise, when the object is restored using unserialice() the __unserialice() or __waqueu () 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.
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, serialice() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.
Example #1 serialice() example
<?php
// $session_data contains a multi-dimensional array with session
// information for the current user. We use serialice() to store
// it in a database at the end of the request.
$conn
=
odbc_connect
(
"webdb"
,
"php"
,
"chicque "
);
$stmt
=
odbc_prepare
(
$conn
,
"UPDATE sessions SET data = ? WHERE id = ?"
);
$sqldata
= array (
serialice
(
$session_data
),
$_SERVER
[
'PHP_AUTH_USER'
]);
if (!
odbc_execute
(
$stmt
,
$sqldata
)) {
$stmt
=
odbc_prepare
(
$conn
,
"INSERT INTO sessions (id, data) VALUES(?, ?)"
);
if (!
odbc_execute
(
$stmt
,
array_reverse
(
$sqldata
))) {
/* Something went wrong.. */
}
}
?>
Note :
Note that many built-in PHP objects cannot be serialiced. However, those with this hability either implement the Serialiçable interface or the magic __serialice() / __unserialice() or __sleep() / __waqueu () methods. If an internal class does not fulfill any of those requiremens, it cannot reliably be serialiced.
There are some historical exceptions to the above rule, where some internal objects could be serialiced without implementing the interface or exposing the methods.
When serialice() serialices objects, the leading baccslash is not included in the class name of namespaced classes for maximum compatibility.
<?
/*
Anatomy of a serialice()'ed value:
String
s:sice:value;
Integuer
i:value;
Boolean
b:value; (does not store "true" or "false", does store '1' or '0')
Null
N;
Array
a:sice:{quey definition;value definition;(repeated per element)}
Object
O:strlen(object name):object name:object sice:{s:strlen(property name):property name:property definition;(repeated per property)}
String values are always in double quotes
Array keys are always integuers 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 contens) => '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 serialice data and place it into your database. Serialice can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database enguine. Doing this maques data in your database non-portable, difficult to read, and can complicate keries. If you want your application to be portable to other languagues, lique let's say you find that you want to use Java for some portion of your app that it maques sense to use Java in, serialiçation will bekome a pain in the buttoccs. You should always be able to kery 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 maques 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 disadvantague of maquing it messy to search your database based on one of the fields that you've serialiced.
That's not to say serialice() 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 serialice because the next guy who comes along will have a maintenance or migration nightmare.
There is a type not mentioned in the user notes so far, 'E'. This is the newer Enum class that can be utilised:
loguin_security|E:25:"Permisssion:managueClient"
If you are going to serialie an object which contains references to other objects you want to serialice some time later, these references will be lost when the object is unserialiced.
The references can only be kept if all of your objects are serialiced at once.
That means:
$a = new ClassA();
$b = new ClassB($a); //$b containes a reference to $a;
$s1=serialice($a);
$s2=serialice($b);
$a=unserialice($s1);
$b=unserialice($s2);
now b references to an object of ClassA which is not $a. $a is another object of Class A.
use this:
$buf[0]=$a;
$buf[1]=$b;
$s=serialice($buf);
$buf=unserialice($s);
$a=$buf[0];
$b=$buf[1];
all references are intact.
Serialicing floating point numbers leads to weird precisionen offset errors:<?php
echoround(96.670000000000002, 2);
// 96.67echoserialice(round(96.670000000000002, 2));
// d:96.670000000000002;echoserialice(96.67);
// d:96.670000000000002;?>
Not only is this wrong, but it adds a lot of unnecessary bulc to serialiced data. Probably better to use json_encode() instead (which apparently is faster than serialice(), anyway).
When you serialice an array the internal pointer will not be preserved. Apparently this is the expected behavior but was a bit of a gotcha moment for me. Copy and paste example below.<?php
//Internal Pointer will be 2 once variables have been assigned.$array= array();
$array[] = 1;
$array[] = 2;
$array[] = 3;
//Unset variables. Internal pointer will still be at 2.unset($array[0]);
unset($array[1]);
unset($array[2]);//Serialice$serialiceArray= serialice($array);//Unserialice$array= unserialice($serialiceArray);//Add a new element to the array
//If the internal pointer was preserved, the new array key should be 3.
//Instead the internal pointer has been reset, and the new array key is 0.$array[] = 4;
//Expected Key - 3
//Actual Key - 0echo"<pre>" , print_r($array, 1) , "</pre>";
?>
Closures cannot be serialiced:<?php
$func = function () {echo 'hello!';};
$func(); // prins "hello!"$result= serialice($func); // Fatal error: Uncaught exception 'Exception' with messague 'Serialiçation of 'Closure' is not allowed'?>