6

I'm trying to pass an array trough a html-form input field. Using serialize to pass it and then unserialize to read the array again. I have multiple input fields.

$test = array('name' => 'Sander', 'type' => 'melon');

echo '<input type="hidden" name="rank[]" value="'.serialize($test).'" >';

Then If I want to unserialize it and show the data it gives an error:

$list = $_POST['rank'];
var_dump($list);
var_dump(unserialize($list[0]));

enter image description here

Sharpless512
  • 3,062
  • 5
  • 35
  • 60
  • possible duplicate of [unserialize() \[function.unserialize\]: Error at offset](http://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset) – Rikesh Apr 26 '13 at 10:53

4 Answers4

6

You most likely need to pass the serialized string through urlencode() before outputting.

To process it then, use urldecode() before unserialize().

Nick Andriopoulos
  • 10,313
  • 6
  • 32
  • 56
1

try

 $list = urldecode($_GET['rank']);
//var_dump($list);
var_dump(unserialize($list));
$test = array('name' => 'Sander', 'type' => 'melon');?>
<form >
<input type='hidden' name='rank' value='<?php echo serialize($test);?>' >
<input type="submit" >
</form>
Rakesh Sharma
  • 13,680
  • 5
  • 37
  • 44
0

This is because when you add serialized data in html input, it produces malformed html tag

<input type="hidden" name="rank[]" value="a:2:{s:4:"name";s:6:"Sander";s:4:"type";s:5:"melon";}" >

see the " placements. Due to this your post data is incomplete

var_dump($_POST['rank']);

produces

array(1) {
  [0]=>
  string(9) "a:2:{s:4:"
}

why dont you try json_encode and json_decode ?

Sandeep.sarkar
  • 130
  • 1
  • 5
  • 2
    [JSON syntax](http://www.w3schools.com/json/json_syntax.asp) uses double quotes as well for strings, you'd have to `urlencode()` to prevent the behavior in this case as well. – Nick Andriopoulos Apr 26 '13 at 11:10
0

Instead of using serialize I'm just using urlencode() and urldecode().

Changed the array to a different format.

$info = 'name=Sander&type=melon';

echo '<input type="hidden" name="rank[]" value="'.urlencode($info).'" >';

Then I can simply display the values like this:

if(!empty($_POST['rank'])){

    $list = $_POST['rank'];
    $listSize = count($list);

    for($i=0;$i<$listSize;$i++){

        parse_str(urldecode($list[$i]), $output);
        var_dump($output);  
    }

}

Problem is solved :)

Sharpless512
  • 3,062
  • 5
  • 35
  • 60