137

My problem is very basic.

I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They just give an example - serialize an array and show an output in an unexplained format. It is really hard to understand the basic concept going through their jargon.

EDIT:

<?php

$a= array( '1' => 'elem 1', '2'=> 'elem 2', '3'=>' elem 3');
print_r($a);
echo ("<br></br>");
$b=serialize($a);
print_r($b);

?>

output:

Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 ) 

a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}

I cannot understand the second output. Besides that, can anyone give an example of a situation that I need to serialize a php array before using it?

Nick
  • 138,499
  • 22
  • 57
  • 95
Istiaque Ahmed
  • 6,072
  • 24
  • 75
  • 141
  • 14
    In case you were still curious about the "secondary output", its fairly simple: a = array, 3 = of size three elements within the {}'s. inside that, you have i=integer/index equalling 1, string of len 6 equalling "elem 1", integer equalling 2.. etc etc.. Its fairly clear when you read it like that. You can imagine multiple levels of arrays/objects being easily contained within, however modification is very unwise, you should really unserialize modify then serialize to ensure consistency. – Grizly Feb 05 '15 at 02:48
  • 2
    @IstiaqueAhmed, Regarding *"can anyone give an example of a situation that I need to serialize a php array before using it"*, there is such an example at http://stackoverflow.com/a/30436890/632951 – Pacerier May 25 '15 at 11:11
  • @grizly thanks man, I've been looking for an answer like that for two years, I didn't know how to explain it nor how to associate the reason for using that feature, thanks for the answer – isaacewing Jun 05 '17 at 03:10

10 Answers10

181

A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.


Take for example this common problem:

How do I pass a PHP array to Javascript?

PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?

Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 ) 

The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:

{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }

Javascript can easily reverse this into an actual Javascript array.

This is just as valid a representation of the same data structure though:

a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}

But pretty much only PHP uses it, there's little support for this format anywhere else.
This is very common and well supported as well though:

<array>
    <element key='1'>elem 1</element>
    <element key='2'>elem 2</element>
    <element key='3'>elem 3</element>
</array>

There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    ur explanation seems to be approaching to what i expected. can u please have a look at my edit? – Istiaque Ahmed Dec 27 '11 at 07:05
  • 1
    what is the explanation of those a,i,s etc in a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";} ? And if u don't mind , an example of serializing the array(might not be relevant to the theme of this post ) to send it to js. – Istiaque Ahmed Dec 27 '11 at 07:39
  • 2
    As far as I'm aware there's hardly a formal specification of that format to be found, but you can guess, can't you? `i:1` = integer 1, `s:6:"elem 1"` = string with 6 characters "elem 1"... And what example are you asking for, I thought I gave one? – deceze Dec 27 '11 at 07:44
  • " But how do you pass this array to Javascript? Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 ) "... just the exact code snippet for it – Istiaque Ahmed Dec 27 '11 at 07:49
  • `echo json_encode($array);` How *exactly* you *pass* it depends on the circumstances. Don't get too hung up on that. – deceze Dec 27 '11 at 07:57
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/6152/discussion-between-istiaque-ahmed-and-deceze) – Istiaque Ahmed Dec 27 '11 at 08:59
  • @deceze How can i convert PHP object to XML Values, can i get help? – Gem Nov 16 '18 at 07:07
29

PHP serialize() unserialize() usage

http://freeonlinetools24.com/serialize

echo '<pre>';
// say you have an array something like this 
$multidimentional_array= array(
    array(
        array("rose", 1.25, 15),
        array("daisy", 0.75, 25),
        array("orchid", 4, 7) 
       ),
    array(
        array("rose", 1.25, 15),
        array("daisy", 0.75, 25),
        array("orchid", 5, 7) 
       ),
    array(
        array("rose", 1.25, 15),
        array("daisy", 0.75, 25),
        array("orchid", 8, 7) 
    )
);

// serialize 
$serialized_array=serialize($multidimentional_array);
print_r($serialized_array);

Which gives you an output something like this

a:3:{i:0;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:4;i:2;i:7;}}i:1;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:5;i:2;i:7;}}i:2;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:8;i:2;i:7;}}}

again if you want to get the original array back just use PHP unserialize() function

$original_array=unserialize($serialized_array, ['allowed_classes' => false]);
var_export($original_array);

I hope this will help

Note: Set allowed_classes to false in unserialize for security reasons. See Warning https://www.php.net/manual/en/function.unserialize.php

PiTheNumber
  • 22,828
  • 17
  • 107
  • 180
tipico
  • 299
  • 3
  • 2
9
<?php
$a= array("1","2","3");
print_r($a);
$b=serialize($a);
echo $b;
$c=unserialize($b, ['allowed_classes' => false]);
print_r($c);

Run this program its echo the output

a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}

Note: Set allowed_classes to false in unserialize for security reasons.


here
a=size of array
i=count of array number
s=size of array values

you can use serialize to store array of data in database
and can retrieve and UN-serialize data to use. See Warning https://www.php.net/manual/en/function.unserialize.php

PiTheNumber
  • 22,828
  • 17
  • 107
  • 180
Manikandan
  • 151
  • 1
  • 6
7

When you want to make your php value storable, you have to turn it to be a string value, that is what serialize() does. And unserialize() does the reverse thing.

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • 1
    'storable' what does it mean? I had gone through the page u referred. can u please show an example in php, and mysql (if necessary) ? – Istiaque Ahmed Dec 27 '11 at 06:52
  • 2
    @Istiaque Ahmed For example, when you want to store an array to a file on the disk, you can't save array directly but turn it to a storable value and that is a string. – xdazz Dec 27 '11 at 07:10
  • but we can directly insert a variable into database without serializing it in php mysql. explanation please. – Istiaque Ahmed Dec 27 '11 at 07:35
  • 9
    *"We can insert a variable into database without serializing it"*. This is true only for fundamental data types (strings, integer, numbers). We cannot insert arrays and objects *directly* into DB or filesystem. That's what `serialize()` and `unserialize()` are made for. – lorenzo-s Dec 27 '11 at 08:23
  • You take some information and do some work with it in your php script ready to store/send it somewhere. You have the option to create a table that exactly matches the expected data, but this is tedious you are essentially doubling your work load because you have to write code that matches too, plus changes in database need changes in code or vice versa. When serialized you can simply create a table with two columns id int(10) and information BLOB. Serialise gives you a string to insert and unserialize returns the data to its original state. There are cases it wont, the php docs cover those. – CodingInTheUK Jun 20 '18 at 13:01
6

Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.

Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().

If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.

alex
  • 479,566
  • 201
  • 878
  • 984
4

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.

it makes really 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.

A good example of serialize() and unserialize() could be like this:

$posts = base64_encode(serialize($_POST));
header("Location: $_SERVER[REQUEST_URI]?x=$posts");

Unserialize on the page

if($_GET['x']) {
   // unpack serialize and encoded URL
   $_POST = unserialize(base64_decode($_GET['x']));
}
chintogtokh
  • 803
  • 1
  • 10
  • 25
Avnish Tiwary
  • 2,188
  • 22
  • 27
2

From http://php.net/manual/en/function.serialize.php :

Generates a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure.

Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).

Unserialize is used to convert the string back to an object.

MrGlass
  • 9,094
  • 17
  • 64
  • 89
  • what is the explanation of 'storable representation' ? – Istiaque Ahmed Dec 27 '11 at 06:50
  • ive only seen serialize used when someone wanted to take a php array and store it in a database. You can serialize, store the output in a standard string field in your database, and then grab and unserialize it when you want to use it again. – MrGlass Dec 27 '11 at 12:52
1

Basically, when you serialize arrays or objects you simply turn it to a valid string format so that you can easily store them outside of the php script.

  1. Use serialize to save the state of an object in database (lets take the User class as an example) Next unserialize the data to load the previous state back to the object (methods are not serializer you need to include object class to be able to use it)
    • user personalization

Note for object you should use magic __sleep and __wakeup methods. __sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.

__wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.

For passing data between php and js you would use json_encode to turn php array to valid json format. Or other way round - use JSON.parese() to convert a output data (string) into valid json object. You would want to do that to make use of local storage. (offline data access)

Antoine
  • 800
  • 3
  • 14
  • 29
DevWL
  • 17,345
  • 6
  • 90
  • 86
  • Why do one need serialize if there is a json_encode? Please explain if you know. Thanks. – Yevgeniy Afanasyev Aug 03 '17 at 00:04
  • 1
    You can benefit from being able to customise magic method that are colled when using serialize and unserialise. That said you can take Json_encode() and json_decode() much futher and each object can handle this functinos in its unique way. This is why you would like to use them. – DevWL Aug 03 '17 at 01:44
  • 1
    There is more much more to it. See this answer for more info https://stackoverflow.com/questions/804045/preferred-method-to-store-php-arrays-json-encode-vs-serialize – DevWL Aug 03 '17 at 03:05
  • 1
    json_encode is faster (depends on PHP version you are using), json decodes as stdClass, serilized object unserialize as actual Class instance, Some configuration has to me made to JSON to preserv UTF-8 encoding unchanged, serialize does not change encoding. If you want to make data cross platform use JSON, If you work only in PHP you might make a use of __sleep and __wakeup magic method to customise the serialization. – DevWL Aug 03 '17 at 03:17
0

Yes, I can. Assume we need to track your system means In your system has more than one admin and subadmin, All of these can insert or update or edit any information.Later you need to know who make this change. For solving this problem you need serialize.

  **Explain:**Create a table named history which stores all changes. Each time there is a change insert a new row in this table. It might have this fields:

  history(id,target_table(name of the table), target_id (ID of the saved entry),create/edit/change data (serialized data of the saved row),date)

I hope this will help you.

-1
preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');

X 47 48 - IR
  • 1,250
  • 1
  • 15
  • 28