128

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';
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
uji
  • 1,603
  • 3
  • 12
  • 12
  • 3
    Why can't you just pass in `$_POST` ? – random Nov 19 '09 at 14:19
  • This really looks messy. But for that approach it has to be. Other approach, little complicated is to assign `query = array('aParam'=> json_encode($arrayOfValues))`. And that you can pass in nicer url with `url_encode(implode('/',$query))`. Url will look like `www.example.com/aParam/[va1,val2,...]`. When receiving you have to json_decode aParam value into array. – Vladimir Vukanac Oct 31 '14 at 17:47

11 Answers11

236

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.

Horen
  • 11,184
  • 11
  • 71
  • 113
Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189
  • 22
    If you are wondering how to get this back into an array, the answer is [parse_str()](http://us1.php.net/manual/en/function.parse-str.php). – Typo Aug 07 '14 at 02:05
  • 1
    I have used this to put the url in the array but don't know how to get the data back. I tried parse_str and couldn't get it to work. I think this would be valuable information – Thomas Williams Sep 07 '16 at 12:37
  • 2
    For anyone running into issues with `http_build_query` returning `param[]` and somtimes `param[index]`. Check out this post: https://stackoverflow.com/questions/11996573/php-url-query-nested-array-with-no-index – stwhite Jul 23 '17 at 17:33
  • 2
    to get back the value you just have to $data = $_GET['aParam']; – dfortun Apr 28 '18 at 11:02
  • @dfortun get back is important you saved a lot of time parse_str() didn't work for me but $data = $_GET['aParam']; is the correct solution – Asesha George Nov 24 '18 at 18:43
  • From PHP 5.1.3 onwards, when using parse_str() to get the data back into an array, you also need to use urldecode to handle the encoded square brackets. E.g. `parse_str(urldecode($urlString), $result);` – Tim Rogers Oct 04 '19 at 10:12
57

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));
Community
  • 1
  • 1
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • 1
    neat! would be nice if it could work with associative arrays too. +1 anyway – knittl Nov 19 '09 at 14:38
  • 3
    knittl: We can do that with a callback function to array_map and passing the keys and values separately. Check it out. – Jordan Running Nov 19 '09 at 15:06
  • but this could still exceed the max size of the GET parameter right? what are the odds if i use sessions instead just like nash mentioned below? – uji Nov 20 '09 at 08:26
  • Well, you can store a more or less unlimited amount of data in a session. The risk with sessions is in URLs breaking when the session expires, or if the user tries to do things e.g. in two tabs at once. If the user bookmarks the page, then comes back after their session expires, will they still get the page they expect? It sounds like you may need to think harder about your architecture and why you're passing around such huge arrays in the first place. – Jordan Running Nov 20 '09 at 14:27
  • +1 good answer and working for me also after one year of posting this answer. – Naveed Jan 06 '11 at 07:08
  • you're using many function that do call other functions(abstraction), this is abstract, abstraction layer.gehrig solution only calls one function, you're calling 3,4(?) functions. – tetris Feb 14 '12 at 19:28
13

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.

nash
  • 2,181
  • 15
  • 16
  • serializing is also a nice way of doing it, but then it's in a not-so-readable form anymore – knittl Nov 19 '09 at 14:26
  • 1
    Yeah, serialize isn't really a clean way of doing things when you're working with urls, because it expands the data so much. Better to go custom. – Kzqai Nov 19 '09 at 16:15
  • the max size of the GET parameter was what i was worried about thats why i was (stupidly) hoping that the parser wont mind if its an array that is passed. i realized just now that it wont work without touching the max size. Thanks anyway nash, I think i will be doing it with sessions – uji Nov 20 '09 at 08:29
  • 5
    You really should not pass untrusted data to unserialize(). Try json_encode() and json_decode() instead. – Mikko Rantalainen Mar 09 '15 at 13:29
6

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);
}
knittl
  • 246,190
  • 53
  • 318
  • 364
  • 1
    Instead of using a "first" variable to skip the first &, you can use a temporary array to store your values, and use implode afterwords. Just for readability. http://php.net/implode – nash Nov 19 '09 at 14:36
6
 <?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

Thusitha Sumanadasa
  • 1,669
  • 2
  • 22
  • 30
3

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.

Viktor
  • 623
  • 4
  • 10
  • 25
1

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'];
Thomas Williams
  • 1,528
  • 1
  • 18
  • 37
0
**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'];
user2638158
  • 99
  • 3
  • 9
0

in the received page you can use:

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

  • 1
    Welcome to Stack Overflow. When adding an answer to a ten year old question with eight other answers it is very important to point out what new aspect of the question your answer addresses. Right now it looks like you have a code only answer that has already been covered by one of the other answers. Please use code formatting for code in future answers. – Jason Aller Jun 06 '20 at 18:29
0

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 !

bensbenj
  • 391
  • 3
  • 7
0

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
)