Page 1 of 1

Problem passing arrays between pages using serialize method

Posted: Tue Dec 13, 2005 11:52 am
by clem_c_rock
Hello,

I'm trying to serialize an array, then throw it into a url stream to pass it to a new page where I will then unserialize the array. When I pass it to the next page and do a print_r( $unserialized_array ), I get no values.

Here's the code I'm trying:

Page 1:

Code: Select all

$array = array();
$array["a"] = "Foo";
$array["b"] = "Bar";
$array["c"] = "Baz";
$array["d"] = "Wom";

$test_array = serialize( $array );

Url string: <a href="page_2.php?serialized_array=<?=$test_array ?>" >
Page 2:

Code: Select all

$this_code_array = array();
$this_code_array = unserialize( urldecode( $_REQUEST['serialized_array'] ) );
print_r( $this_code_array ); // will not print anything[php][/php]

Posted: Tue Dec 13, 2005 12:02 pm
by choppsta
I think you need to urlencode on the first page, and you don't need to decode on the second if you just use $_GET. Also, when outputting as HTML you should also use htmlspecialchars() so that any & become &, etc.

Code: Select all

$test_array = serialize($array);

$url = 'page_2.php?serialized_array='.urlencode($test_array);
$url = htmlspecialchars($url);

$link = '<a href="'.$url.'">My Link</a>';
Then Just:

Code: Select all

$test_array = unserialize($_GET['serialized_array']);

When I do this

Posted: Tue Dec 13, 2005 12:55 pm
by clem_c_rock
I get a strange string which is as follows:

a%3A4%3A%7Bs%3A1%3A%22a%22%3Bs%3A3%3A%22Foo%22%3Bs%3A1%3A%22b%22%3Bs%3A3%3A%22Bar%22%3Bs%3A1%3A%22c%22%3Bs%3A3%3A%22Baz%22%3Bs%3A1%3A%22d%22%3Bs%3A3%3A%22Wom%22%3B%7D

This looks like something can't really use because the array I will be sending to page 2 will be quite large.

Any other ideas?

Wait - let me take that back

Posted: Tue Dec 13, 2005 12:59 pm
by clem_c_rock
I believe I doubled up on the urlencode of the variable on page 1.

Looks like it's working well - SWEET!

Thanks a lot.