PHP – Passing Array in URL and Retrieve with Get

To pass an array in a url use the following:

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

To retrieve the array use the following:

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

Here is an explination of whats going on:

//create the associated array
$args['bid'] = 2;
$args['pid'] = 1806;
$args['mid'] = true;

//serialize and encode array to make it safe for transferring in the url
$serialized = rawurlencode(serialize($args));

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

//url with included serialized and encoded array
testpage.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’])));

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

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

//strip slashes and make it ready to be unserialized
string(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’]))));

//unserialize the array
//now we have our origional associated array
array(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 *