string serialize ( mixed value)
mixed unserialize ( string input)
string urlencode ( string text)
string urldecode ( string encoded)
As arrays are complex data types, you cannot see their contents directly. If you try printing out the value of an array, you will see PHP just outputs "Array", which means that passing the value of an array through a link requires a lot of work. Luckily, PHP comes to the rescue with four functions that do all the hard work for you: serialize(), unserialize(), urlencode(), and urldecode().
Serialize() converts an array, given as its only parameter, into a normal string that you can save in a file, pass in a URL, etc. Unserialize() is the opposite of serialize() - it takes a serialize()d string and converts it back to an array.
Urlencode() and urldecode() also work in tandem, and convert the string that is sent to them as their only parameter into a version that is safe to be passed across the web. All characters that aren't letters and numbers get converted into web-safe codes that can be converted back into the original text using urldecode().
Passing arrays across pages is best done using urlencode() and urldecode(), however you should consider using them both on any data you pass across the web, just to make sure there are no incompatible characters in there.
Take a look at this next script:
<?php $array["a"] = "Foo"; $array["b"] = "Bar"; $array["c"] = "Baz"; $array["d"] = "Wom"; $str = serialize($array); $strenc = urlencode($str); print $str . "\n"; print $strenc . "\n"; ?>
That will output two lines (the second of which I've forced to wrap so that it appears properly!):
The first is the direct, serialize()d output of our array, and you can see how it works by looking through the text inside there. The second line contains the urlencode()d serialize()d array, and is very hard to read. Despite being hard to read, the latter is wholly web safe, and there much better to use.
Once your array is in text form, you can do with it as you please. To return back to the original array, it needs to be urldecode()d, then unserialize()d, like this:
<?php $arr = unserialize(urldecode($strenc)); var_dump($arr); ?>
Author's Note: If you want to transfer binary data over the web, you should use rawurlencode() and rawurldecode() as opposed to urlencode() and urldecode(), as the raw versions are binary-safe.
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Summary >>
Previous chapter: Arrays in strings
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.