This tutorial will talk you through the basic steps involved in submitting a serialized array in a form using PHP. Although this can be a straightforward procedure there are a couple of pitfalls to be aware of.
Why Serialize an Array?
There are lots of reasons for wanting to serialize your data. especially if you are passing sensitive information. Serialization may not be a word, but its a great way to make data more secure and tamper proof. with tools such as url params and the web developer toolbar, it has never been easier to hack websites, so the rule of thumb should always be, leave nothing to chance.
Serialized Example
To overcome the problems you may encounter in serializing an array, consider the following example. we have an array that we want to post through in a form and unserliaze on the other side for further use. Your code would look something like this:
$foo = array("hank", "frank", "tank");
?>
<form action="recieve.php" method="post">
<input name="names" type="text" value="<?php print_r(serialize($foo)); ?>" />
<input type="submit" value="submit">
</form>
This however will not work. the serialized array, if you check the code you will see it looks like this “a:3:{i:0;s:4:“. The reason this breaks is a simple case of “”, instead if we try that same code with single quotes around the value attribute we get a:3:{i:0;s:4:”hank”;i:1;s:5:”frank”;i:2;s:4:”tank”;}, (check out the live example), which is the complete array: the code to get this would look like this:
<?php
$foo = array("hank", "frank", "tank");
?>
<form method="post" action="recieve.php" name="formExample">
<input type="text" name="names" value='<?php print_r(serialize($foo)); ?>' />
<input type="submit" value="submit">
</form>
Now we have the fully serialized array we can pass it through and pull it out the other side of the form. Once we post the form through to the recieve.php we hit another problem. consider the following code:
<?php
$names = unserialize($_POST['names']);
echo($names);
?>
you will find that the code will not output anything, this is yet another pitfall. In order to get the array back out in a usable format we need to use the stripslashes() to remove the uneccesary back slashes that are preventing our array from unserializing. your code would want to look like this:
<?php
$names = unserialize(stripslashes($_POST['names']) );
echo($names);
?>
this will then give you the the your array safely unserilized and ready for use on the other side.
Try It For Yourself
To test this out for yourslef check out the demo, or download the source code and try it out. Good Luck!