Hudzilla.org - the homepage of Paul Hudson
Contents > Arrays Wish List | Report Bug | About Me ]

5.11     Saving arrays: serialize(), unserialize(), urlencode(), and urldecode()

This is NOT the latest copy of this book; click here for the latest version.

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!):

a:4:{s:1:"a";s:3:"Foo";s:1:"b";s:3:"Bar";s:1:"c";s:3:"Baz";s:1:"d";s:3:"Wom";}
a%3A4%3A%7Bs%3A1%3A%22a%22%3Bs%3A3%3A%22Foo%22%3Bs%3A1%3A%22b%22%3Bs%3A0%3A%22
%22%3Bs%3A1%3A%22c%22%3Bs%3A3%3A%22Baz%22%3Bs%3A1%3A%22d%22%3Bs%3A3%3A%22Wom%22%3B%7D

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.





<< 5.10 Arrays in strings   5.12 Summary >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
ritwickpal@yahoo.co.in - 20 Aug 2008

Hi,
thanks for the code. So far so good. I'm developing a shopping application with Yahoo shopping. The results are returned in serialized PHP. I've successfully unserialized it.
Now I want to know, how to display the results from an unserialized PHP matter in PHP4? ie how to extract the product name, image etc serially from the data? ( http://developer.yahoo.com/common/phpserial.html )
Thanks in advance.
- Ritwick

A PHP User - 20 Aug 2008

I am new to php pls help me?
i want to pass one array of string across the page and in next page i want to store it in databse any help?

A PHP User - 20 Aug 2008

Peter B--you need to urldecode() each one of those HTTP_POST_VAR['...'] items. But as the previous posts noted, you should not trust data entered by end users. You will need to validate it first, and protect things like apostrophes in the user's input.

peter b - 20 Aug 2008

I have a php file that takes input from my textfields in flah mx and stores it in my database however when my values are passed to mysql table the data is not properly stored in a correct format non alphanumerical characters and spaces are replaced by %20 etc. I realise i need to unserialize the data somewhere along the line have attempted it, but cant seem to get this working can someone help me pleasse!! im pulling my haitr out.
this is my php code any help would be much appreciated iam running php version 4.3.10

<?php
//this line includes the database connection variables
include_once("connect.php");

$success = 1;

$upd_str = "UPDATE products SET brand='".$HTTP_POST_VARS['brand']."', ";
$upd_str .= "florName='".$HTTP_POST_VARS['florName']."', ";
$upd_str .= "species='".$HTTP_POST_VARS['species']."', ";
$upd_str .= "code='".$HTTP_POST_VARS['code']."', ";
$upd_str .= "image='".$HTTP_POST_VARS['image']."', ";
$upd_str .= "descript='".$HTTP_POST_VARS['descript']."', ";
$upd_str .= "florType='".$HTTP_POST_VARS['florType']."'";
$upd_str .= " WHERE pID=".$HTTP_POST_VARS['pID'];

if (!mysql_query ($upd_str)) {
$success = 0;
$msg = 'Record could not be updated';
} else {
$msg = 'Record for pID '.$HTTP_POST_VARS['pID'].' was updated successfully. Refreshing display...';
}

echo '&success='.$success.'&msg='.$msg.'&';

?>

A PHP User - 20 Aug 2008

Could you explain more because i honestly dont understand what you meant by "allowed for user to pass "s and..."

capi@abeeda.com - 20 Aug 2008

Just a special note, the function urldecode() turned out to be one of phpBBs big mistakes. It allowed for users to pass "s and therefore pass in all sorts of MySQL data. It's one of the big pieces of the santy bug. Though the urldecode() itself was not at fault. you should remember to properly sanatize information from the user. Don't trust anything, including yourself.



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is seven plus four?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow