PHP – Passing Array in URL and Retrieve with Get

To pass an array in a url use the following:

1<?php $serialized = rawurlencode(serialize($args)); ?>
2<a href="testpage.php?args=<!--?php echo $args ?-->">Test Page</a>

To retrieve the array use the following:

1<?php $args = unserialize(stripslashes(rawurldecode($_GET['args']))); ?>

Here is an explination of whats going on:

1//create the associated array
2$args['bid'] = 2;
3$args['pid'] = 1806;
4$args['mid'] = true;
5 
6//serialize and encode array to make it safe for transferring in the url
7$serialized = rawurlencode(serialize($args));

<a href=”testpage.php?args=“>Test Page</a>

1//url with included serialized and encoded array
2testpage.php?args=a%3A3%3A{s%3A3%3A%22bid%22%3Bi%3A2%3Bs%3A3%3A%22pid%22%3Bi%3A1806%3Bs%3A3%3A%22mid%22%3Bb%3A1%3B}

var_dump(rawurldecode($_GET[‘args’])));

1//result of decoded array, notice the extra slashes in the serialized array
2string(57) "a:3:{s:3:\"bid\";i:2;s:3:\"pid\";i:1806;s:3:\"mid\";b:1;}"

var_dump(stripslashes(rawurldecode($_GET[‘args’]))));

1//strip slashes and make it ready to be unserialized
2string(51) "a:3:{s:3:"bid";i:2;s:3:"pid";i:1806;s:3:"mid";b:1;}"

var_dump(unserialize(stripslashes(rawurldecode($_GET[‘args’]))));

1//unserialize the array
2//now we have our origional associated array
3array(3) { ["bid"]=> int(2) ["pid"]=> int(1806) ["mid"]=> bool(true) }
Posted in: PHP

Leave a Reply

Your email address will not be published. Required fields are marked *