PHP Variables Encapsulating Complex Data Types in a String - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Variables Encapsulating Complex Data Types in a String - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Wednesday, May 22, 2019

PHP Variables Encapsulating Complex Data Types in a String

PHP Variables




Encapsulating Complex Data Types in a String

Problem

You want a string representation of an array or object for storage in a file or database. This string should be easily reconstitutable into the original array or object.

Solution

Use serialize() to encode variables and their values into a textual form:

            $pantry = array('sugar' => '2 lbs.','butter' => '3 sticks');
            $fp = fopen('/tmp/pantry','w') or die ("Can't open pantry");
            fputs($fp,serialize($pantry));
            fclose($fp);

To re-create the variables, use unserialize():

            // $new_pantry will be the array:
            // array('sugar' => '2 lbs.','butter' => '3 sticks'
            $new_pantry = unserialize(file_get_contents('/tmp/pantry'));

For easier interoperability with other languages (at a slight performance cost), use json_encode() to serialize data:

            $pantry = array('sugar' => '2 lbs.','butter' => '3 sticks');
            $fp = fopen('/tmp/pantry.json','w') or die ("Can't open pantry");
            fputs($fp,json_encode($pantry));
            fclose($fp);

And use json_decode() to re-create the variables:

            // $new_pantry will be the array:
            // array('sugar' => '2 lbs.','butter' => '3 sticks')
            $new_pantry = json_decode(file_get_contents('/tmp/pantry.json'), TRUE);

Discussion

The PHP serialized string that is reconstituted into $pantry looks like:

            a:2:{s:5:"sugar";s:6:"2 lbs.";s:6:"butter";s:8:"3 sticks";}

The JSON-encoded version looks like:

            {"sugar":"2 lbs.","butter":"3 sticks"}

The extra business in the serialized string that’s not in the JSON string encodes the types and lengths of the values. This makes it uglier to look at but a little faster to decode. If you’re just shuttling data among PHP applications, native serialization is great. If you need to work with other languages, use JSON instead.

Both native serialization and JSON store enough information to bring back all the values in the array, but the variable name itself isn’t stored in either serialized representation. JSON can’t distinguish between objects and associative arrays in its serialization format, so you have to choose which you want when you call json_decode(). 

A second argument of true, as in the previous example, produces associative arrays. Without that argument, the same JSON would be decoded into an object of class stdClass with two properties: sugar and butter.

When passing serialized data from page to page in a URL, call urlencode() on the data to make sure URL metacharacters are escaped in it:

            $shopping_cart = array('Poppy Seed Bagel' => 2,
                                                  'Plain Bagel' => 1,
                                                  'Lox' => 4);

            print '<a href="next.php?cart='.urlencode(serialize($shopping_cart)).
                        '">Next</a>';

Serialized data going into a database always needs to be escaped as well. Explains how to safely escape values for insertion into a database. When you unserialize an object, PHP automatically invokes its __wakeUp() method.

This allows the object to reestablish any state that’s not preserved across serialization, such as database connection. This can alter your environment, so be sure you know what you’re unserializing.


No comments:

Post a Comment

Post Top Ad