Problem passing arrays between pages using serialize method

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
clem_c_rock
Forum Commoner
Posts: 46
Joined: Mon Jun 07, 2004 9:18 am

Problem passing arrays between pages using serialize method

Post 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]
choppsta
Forum Contributor
Posts: 114
Joined: Thu Jul 03, 2003 11:11 am

Post 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']);
clem_c_rock
Forum Commoner
Posts: 46
Joined: Mon Jun 07, 2004 9:18 am

When I do this

Post 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?
clem_c_rock
Forum Commoner
Posts: 46
Joined: Mon Jun 07, 2004 9:18 am

Wait - let me take that back

Post 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.
Post Reply