Search code examples
phpformsserializationhidden-field

PHP: Serializing/Deserializing hidden array in form


Working with PHP 5.5.9

I'm trying to send a hidden serialized array to a form. I have the form and the action script in the same file, using

 <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">

I initialize the array at the beginning of the file:

 <?php $sports = array("Basketball", "Football", "Handball");?>

I add an ok button to my form:

 <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
    <input type="hidden" name="serializedData" value="<?php echo serialize($sports);?>">
    <input type="submit" name="okButton" value="OK"><br>
</form>

Now I'm trying to deserialize the hidden array when the user presses the ok Button. I want the code also to print the contents of the array

if(isset($_POST['okButton'])) {
   $sports_new = unserialize($_POST['serializedData']);

   // Show array
   for($i = 0; $i < count($sports_new); $i++) {
                    print $sports_new[$i]."<br/>";
   }       

But nothing is shown. I guess that the input hidden element of my form does not get any data. But the $sports array is initialized at the beginning of the file. Why does it not get serialized? Or does my problem rely on the deserializing code?


Solution

  • Ok, I followed your hints. Needed to convert the htmlentities before:

     <input type="hidden" name="serializedData" value="<?php echo htmlentities(serialize($sports));?>">