Don't understand serialize() - php

I'm looking at this function: serialize() for PHP and I don't really understand what is it's function. Can someone provide a simple example with output?

Basically, the goal of serialize is to transform any (alsmost) kind of data to a string, so it can be transmitted, stored, ...
A quick example :
$my_array = array(
'a' => 10,
'glop' => array('test', 'blah'),
);
$serialized = serialize($my_array);
echo $serialized;
Will get you this output :
a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}
And, later, you can unserialize that string, to get the original data back :
$serialized = 'a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}';
$data = unserialize($serialized);
var_dump($data);
Will get you :
array
'a' => int 10
'glop' =>
array
0 => string 'test' (length=4)
1 => string 'blah' (length=4)
Common uses include :
Ability to transmit (almost) any kind of PHP data from one PHP script to another
Ability to store (almost) any kind of PHP data in a single database field -- even if it's not quite a good practice on the database-side, it can sometimes be usefull
Ability to store data in some caching mecanism (APC, memcached, files, ...), in which you can only store strings
Note, though, that using serialize is great when you are only working with PHP (as it's a PHP-specific format, that's able to work with almost any kind of PHP data, and is really fast) ; but it's not that great when you have to also work with something else than PHP (as it's PHP-specific). In those cases, you can use XML, JSON (see json_encode and json_decode), ...
In the PHP manual, you can also read the Object Serialization section, btw.

If you want to save an array or object normalised in a database row for example, serialize() (and unserialize()) are your friends, because you can't store an array or object flattened without first turning it into a string.
json_encode() and json_decode() are similar except they encode as JSON.

See this example, should be pretty clear.

Related

To call a particular column/field from an array using PHP [duplicate]

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?
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.
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
<?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
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.
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.
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']));
}
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.
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.
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)
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.
preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');

How to extract data from (array?) with colons [duplicate]

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?
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.
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
<?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
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.
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.
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']));
}
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.
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.
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)
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.
preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');

How do i format a template string with this kind of data? [duplicate]

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?
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.
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
<?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
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.
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.
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']));
}
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.
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.
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)
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.
preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');

How to use php serialize() and unserialize()

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?
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.
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
<?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
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.
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.
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']));
}
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.
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.
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)
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.
preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');

Problem with json_encode()

i have an simple array:
array
0 => string 'Kum' (length=3)
1 => string 'Kumpel' (length=6)
when I encode the array using json_encode(), i get following:
["Kum","Kumpel"]
My question is, what is the reason to get ["Kum","Kumpel"] instead of { "0" : "Kum", "1" : "Kumpel" }?
"{}" brackets specify an object and "[]" are used for arrays according to JSON specification. Arrays don't have enumeration, if you look at it from memory allocation perspective. It's just data followed by more data, objects from other hand have properties with names and the data is assigned to the properties, therefore to encode such object you must also pass the correct property names. But for array you don't need to specify the indexes, because they always will be 0..n, where n is the length of the array - 1, the only thing that matters is the order of data.
$array = array("a","b","c");
json_encode($array); // ["a","b","c"]
json_encode($array, JSON_FORCE_OBJECT); // {"0":"a", "1":"b","2":"c"}
The reason why JSON_FORCE_OBJECT foces it to use "0,1,2" is because to assign data to obeject you must assign it to a property, since no property names are given by developer (only the data) the encoder uses array indexes as property names, because those are the only names which would make sense.
Note: according to PHP manual the options parameters are only available from PHP 5.3.
For older PHP versions refer to chelmertz's answer for a way to make json_encode to use indexes.
As Gumbo said, on the JS-side it won't matter. To force PHP into it, try this:
$a = new stdClass();
$a->{0} = "Kum";
$a->{1} = "Kumpel";
echo json_encode($a);
Not that usable, I'd stick with the array notation.
Just cast as an object and it will work fine...the JSON_FORCE_OBJECT parameter does exactly the same thing.
json_encode((object)$array);
Don't forget to convert it back into a php array so you can access its values in php:
$array = (object)$array;
$array = (array)$array;
json_encode($array);
Since you’re having a PHP array with just numeric keys, there is no need to use a JavaScript object. But if you need one, try Maiku Mori’s suggestion.
I personally think this is a bug that needs to be fixed in PHP. JSON_FORCE_OBJECT is absolutely not an answer. If you try to do any sort of generic programming you get tripped up constantly. For example, the following is valid PHP:
array("0" => array(0,1,2,3), "1" => array(4,5,6,7));
And should be converted to
{"0": [0,1,2,3], "1": [4,5,6,7]}
Yet PHP expects me to either accept
[[0,1,2,3],[4,5,6,7]]
or
{"0":{"0":1,"1":1,"2":2,"3":3},"1":{"0":4,"1":5,"2":6,"3":7}}
Neither of which are right at all. How can I possibly decode an object like that? What possible reason is there to ever change something that is clearly using strings as indexes? It's like PHP was trying to be clever to help out idiotic people who can't differentiate strings from ints, but in the process messed up anyone legitimately using strings as indexes, regardless of what the value COULD be turned into.

Categories