Passing arrays as url parameter

PhpArraysUrl

Php Problem Overview


What is the best way that I can pass an array as a url parameter? I was thinking if this is possible:

$aValues = array();

$url = 'http://www.example.com?aParam='.$aValues;

or how about this:

$url = 'http://www.example.com?aParam[]='.$aValues;

Ive read examples, but I find it messy:

$url = 'http://www.example.com?aParam[]=value1&aParam[]=value2&aParam[]=value3';

Php Solutions


Solution 1 - Php

There is a very simple solution: http_build_query(). It takes your query parameters as an associative array:

$data = array(
    1,
    4,
    'a' => 'b',
    'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));

will return

string(63) "aParam%5B0%5D=1&aParam%5B1%5D=4&aParam%5Ba%5D=b&aParam%5Bc%5D=d"

http_build_query() handles all the necessary escaping for you (%5B => [ and %5D => ]), so this string is equal to aParam[0]=1&aParam[1]=4&aParam[a]=b&aParam[c]=d.

Solution 2 - Php

Edit: Don't miss Stefan's solution above, which uses the very handy http_build_query() function: https://stackoverflow.com/a/1764199/179125

knittl is right on about escaping. However, there's a simpler way to do this:

$url = 'http://example.com/index.php?';
$url .= 'aValues[]=' . implode('&aValues[]=', array_map('urlencode', $aValues));

If you want to do this with an associative array, try this instead:

PHP 5.3+ (lambda function)

$url = 'http://example.com/index.php?';
$url .= implode('&', array_map(function($key, $val) {
    return 'aValues[' . urlencode($key) . ']=' . urlencode($val);
  },
  array_keys($aValues), $aValues)
);

PHP <5.3 (callback)

function urlify($key, $val) {
  return 'aValues[' . urlencode($key) . ']=' . urlencode($val);
}

$url = 'http://example.com/index.php?';
$url .= implode('&amp;', array_map('urlify', array_keys($aValues), $aValues));

Solution 3 - Php

Easiest way would be to use the serialize function.

It serializes any variable for storage or transfer. You can read about it in the php manual - serialize

The variable can be restored by using unserialize

So in the passing to the URL you use:

$url = urlencode(serialize($array))

and to restore the variable you use

$var = unserialize(urldecode($_GET['array']))

Be careful here though. The maximum size of a GET request is limited to 4k, which you can easily exceed by passing arrays in a URL.

Also, its really not quite the safest way to pass data! You should probably look into using sessions instead.

Solution 4 - Php

please escape your variables when outputting (urlencode).

and you can’t just print an array, you have to build your url using a loop in some way

$url = 'http://example.com/index.php?'
$first = true;
foreach($aValues as $key => $value) {
  if(!$first) $url .= '&amp';
  else $first = false;
  $url .= 'aValues['.urlencode($key).']='.urlencode($value);
}

Solution 5 - Php

 <?php
$array["a"] = "Thusitha";
$array["b"] = "Sumanadasa";
$array["c"] = "Lakmal";
$array["d"] = "Nanayakkara";

$str = serialize($array);
$strenc = urlencode($str);
print $str . "\n";
print $strenc . "\n";
?> 

print $str . "\n"; gives a:4:{s:1:"a";s:8:"Thusitha";s:1:"b";s:10:"Sumanadasa";s:1:"c";s:6:"Lakmal";s:1:"d";s:11:"Nanayakkara";} and

print $strenc . "\n"; gives

a%3A4%3A%7Bs%3A1%3A%22a%22%3Bs%3A8%3A%22Thusitha%22%3Bs%3A1%3A%22b%22%3Bs%3A10%3A%22Sumanadasa%22%3Bs%3A1%3A%22c%22%3Bs%3A6%3A%22Lakmal%22%3Bs%3A1%3A%22d%22%3Bs%3A11%3A%22Nanayakkara%22%3B%7D

So if you want to pass this $array through URL to page_no_2.php,

ex:-

$url ='http://page_no_2.php?data=".$strenc."';

To return back to the original array, it needs to be urldecode(), then unserialize(), like this in page_no_2.php:

    <?php
    $strenc2= $_GET['data'];
    $arr = unserialize(urldecode($strenc2));
    var_dump($arr);
    ?>
 

gives

 array(4) {
  ["a"]=>
  string(8) "Thusitha"
  ["b"]=>
  string(10) "Sumanadasa"
  ["c"]=>
  string(6) "Lakmal"
  ["d"]=>
  string(11) "Nanayakkara"
}

again :D

Solution 6 - Php

I do this with serialized data base64 encoded. Best and smallest way, i guess. urlencode is to much wasting space and you have only 4k.

Solution 7 - Php

This isn't a direct answer as this has already been answered, but everyone was talking about sending the data, but nobody really said what you do when it gets there, and it took me a good half an hour to work it out. So I thought I would help out here.

I will repeat this bit

$data = array(
'cat' => 'moggy',
'dog' => 'mutt'
);
$query = http_build_query(array('mydata' => $data));
$query=urlencode($query);

Obviously you would format it better than this www.someurl.com?x=$query

And to get the data back

parse_str($_GET['x']);
echo $mydata['dog'];
echo $mydata['cat'];

Solution 8 - Php

**in create url page**

$data = array(
		'car' => 'Suzuki',
		'Model' => '1976'
		);
$query = http_build_query(array('myArray' => $data));
$url=urlencode($query);	
	
echo" <p><a href=\"index2.php?data=".$url."\"> Send </a><br /> </p>";

**in received page**

parse_str($_GET['data']);
echo $myArray['car'];
echo '<br/>';
echo $myArray['model'];

Solution 9 - Php

in the received page you can use:

parse_str($str, $array); var_dump($array);

Solution 10 - Php

You can combine urlencoded with json_encode

Exemple:

<?php

$cars = array
(
    [0] => array
        (
            [color] => "red",
            [name] => "mustang",
            [years] => 1969
        ),

    [1] => array
        (
            [color] => "gray",
            [name] => "audi TT",
            [years] => 1998
        )

)

echo "<img src='your_api_url.php?cars=" . urlencode(json_encode($cars)) . "'/>"

?>

Good luck ! 

Solution 11 - Php

Very easy to send an array as a parameter.

User serialize function as explained below

$url = www.example.com

$array = array("a" => 1, "b" => 2, "c" => 3);

To send array as a parameter

$url?array=urlencode(serialize($array));

To get parameter in the function or other side use unserialize

$param = unserialize(urldecode($_GET['array']));

echo '<pre>';
print_r($param);
echo '</pre>';

Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionujiView Question on Stackoverflow
Solution 1 - PhpStefan GehrigView Answer on Stackoverflow
Solution 2 - PhpJordan RunningView Answer on Stackoverflow
Solution 3 - PhpnashView Answer on Stackoverflow
Solution 4 - PhpknittlView Answer on Stackoverflow
Solution 5 - PhpThusitha SumanadasaView Answer on Stackoverflow
Solution 6 - PhpViktorView Answer on Stackoverflow
Solution 7 - PhpThomas WilliamsView Answer on Stackoverflow
Solution 8 - Phpuser2638158View Answer on Stackoverflow
Solution 9 - PhpCarlosPView Answer on Stackoverflow
Solution 10 - PhpbensbenjView Answer on Stackoverflow
Solution 11 - PhpAmmar KhaliqView Answer on Stackoverflow