Passing arrays as url parameter - php

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';

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.

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('&', array_map('urlify', array_keys($aValues), $aValues));

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.

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);
}

<?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

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.
why: http://mizine.de/html/array-ueber-get-url-parameter-uebergeben/
how: https://gist.github.com/vdite/79919fa33a3e4fbf505c

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'];

**in create url page**
$data = array(
'car' => 'Suzuki',
'Model' => '1976'
);
$query = http_build_query(array('myArray' => $data));
$url=urlencode($query);
echo" <p> Send <br /> </p>";
**in received page**
parse_str($_GET['data']);
echo $myArray['car'];
echo '<br/>';
echo $myArray['model'];

in the received page you can use:
parse_str($str, $array);
var_dump($array);

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 ! 🐘

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
)

Related

PHP - Implode, Explode works sometimes, and sometimes not? [duplicate]

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';
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.
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('&', array_map('urlify', array_keys($aValues), $aValues));
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.
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);
}
<?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
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.
why: http://mizine.de/html/array-ueber-get-url-parameter-uebergeben/
how: https://gist.github.com/vdite/79919fa33a3e4fbf505c
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'];
**in create url page**
$data = array(
'car' => 'Suzuki',
'Model' => '1976'
);
$query = http_build_query(array('myArray' => $data));
$url=urlencode($query);
echo" <p> Send <br /> </p>";
**in received page**
parse_str($_GET['data']);
echo $myArray['car'];
echo '<br/>';
echo $myArray['model'];
in the received page you can use:
parse_str($str, $array);
var_dump($array);
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 ! 🐘
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
)

Create an array from content in string in PHP

I have a string that takes multiple key values and i would like to get these value and create an array from it.
The string will be built the same way but might contain more keys or less keys. An example of a string is this
"title:'this is the new title', msg:'this_is_updated', body:'this is the new body text'
So i need some way to to turn these keys from the string into an array that looks like this
$array['customMessage'] = [
'title' => 'this is the new title',
'msg' => 'this_is_updated',
'body' => 'this is the new body'
];
if its allways in this format
key: val, key:val
as you have showed then use explode
$str = "title:'this is the new title', msg:'this_is_updated', body:'this is the
new body text'";
foreach(explode(',', $str) as $val)
{
$item = explode(':', $val);
$array['customMessage'][trim($item[0])] = trim($item[1],"'");
}
First of all, you should always try to use an already existing format. JSON is perfect for that, for example, and PHP has already existing functions to work with that.
If that's not possible, for whatever reason, you can use the following to achive your result string:
$string = "title:'this is the new title', msg:'this_is_updated', body:'this is the new body text'";
$firstExplode = explode(',', $string);
foreach($firstExplode as $explode) {
$val = explode(':', $explode);
$arr[$val[0]] = $val[1];
}
var_dump($arr);
Output:
array(3) {
["title"]=>
string(23) "'this is the new title'"
[" msg"]=>
string(17) "'this_is_updated'"
[" body"]=>
string(27) "'this is the new body text'"
}
this is the logic
$str = "title:'this is the new title', msg:'this_is_updated', body:'this is the new body text' ";
$str1 = explode(',', $str);
$array['customMessage'] = array();
foreach ($str1 as $key => $value) {
$str2 = explode(':', $value);
$array['customMessage'][$str2[0]] = $str2[1];
}
print_r($array['customMessage']);die;
If possible, you can build the string in a JSON format and use json_decode() like this:
$json = '{
"title":"this is the new title",
"msg":"this_is_updated",
"body":"this is the new body text"
}';
$array = json_decode($json, true);
$arrayFinal = array();
$arrayFinal['customMessage'] = $array;
echo '<pre>';
print_r($arrayFinal);
echo '</pre>';
This will give the following output:
Array
(
[customMessage] => Array
(
[title] => this is the new title
[msg] => this_is_updated
[body] => this is the new body text
)
)
The string is a simple JSON object, just decode with this native function
$array = json_decode($string)

Extract parameter from a string

I have to extract a string like this:
index.php?module=Reports&action=abc&rname=Instantpayment
Now my task is to extract report, action and rname value in PHP.
I have tried by using explode(), but I am not able to extract module.
How can I do it?
You could use parse_str() in this case:
$string = 'index.php?module=Reports&action=abc&rname=Instantpayment';
$string = substr($string, strpos($string, '?')+1); // get the string from after the question mark until end of string
parse_str($string, $data); // use this function, stress free
echo '<pre>';
print_r($data);
Should output:
Array
(
[module] => Reports
[action] => abc
[rname] => Instantpayment
)
$yourUrl="module=Reports&action=abc&rname=Instantpayment"
$exploded_array = array();
parse_str($yourUrl, $exploded_array);
$exploded_array['module'];
$exploded_array['action'];
$exploded_array['rname'];
Use $_GET to get query strings from the URL
echo $_GET['module']; //Reports
echo $_GET['action']; // abc
echo $_GET['rname']; // Instantpayment
For getting from the string try explode():
$str ='index.php?module=Reports&action=abc&rname=Instantpayment';
$e = explode('?', $str);
$e1 = explode('&', $e[1]);
foreach($e1 as $v) {
$ex = explode('=', $v);
$newarr[$ex[0]] = $ex[1];
}
print_r($newarr); // Use this array of values you want.
//Array ( [module] => Reports [action] => abc [rname] => Instantpayment )
echo $newarr['module'];
echo $newarr['action'];
echo $newarr['rname'];
You have to access the globale GET variable:
$_GET['module']
$_GET['action']
$_GET['rname']
Try this:
<?php
$temp = "index.php?module=Reports&action=abc&rname=Instantpayment";
$t1 = explode("=",$temp);
for ($i = 1; $i < sizeof($t1); $i++)
{
$temp = explode("&", $t1[$i]);
echo $temp[0] . "\n";
}
?>

PHP read and write JSON from file

I have the following JSON in a file list.txt:
{
"bgates":{"first":"Bill","last":"Gates"},
"sjobs":{"first":"Steve","last":"Jobs"}
}
How do I add "bross":{"first":"Bob","last":"Ross"} to my file using PHP?
Here's what I have so far:
<?php
$user = "bross";
$first = "Bob";
$last = "Ross";
$file = "list.txt";
$json = json_decode(file_get_contents($file));
$json[$user] = array("first" => $first, "last" => $last);
file_put_contents($file, json_encode($json));
?>
Which gives me a Fatal error: Cannot use object of type stdClass as array on this line:
$json[$user] = array("first" => $first, "last" => $last);
I'm using PHP5.2. Any thoughts? Thanks!
The clue is in the error message - if you look at the documentation for json_decode note that it can take a second param, which controls whether it returns an array or an object - it defaults to object.
So change your call to
$json = json_decode(file_get_contents($file), true);
And it'll return an associative array and your code should work fine.
The sample for reading and writing JSON in PHP:
$json = json_decode(file_get_contents($file),TRUE);
$json[$user] = array("first" => $first, "last" => $last);
file_put_contents($file, json_encode($json));
Or just use $json as an object:
$json->$user = array("first" => $first, "last" => $last);
This is how it is returned without the second parameter (as an instance of stdClass).
You need to make the decode function return an array by passing in the true parameter.
json_decode(file_get_contents($file),true);
Try using second parameter for json_decode function:
$json = json_decode(file_get_contents($file), true);
This should work for you to get the contents of list.txt file
$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));
$context=stream_context_create($headers);
$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);
$str=utf8_encode($str);
$str=json_decode($str,true);
print_r($str);
If you want to display the JSON data in well defined formate you can modify the code as:
file_put_contents($file, json_encode($json,TRUE));
$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));
$context=stream_context_create($headers);
$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);
$str1=utf8_encode($str);
$str1=json_decode($str1,true);
foreach($str1 as $key=>$value)
{
echo "key is: $key.\n";
echo "values are: \t";
foreach ($value as $k) {
echo " $k. \t";
# code...
}
echo "<br></br>";
echo "\n";
}
When you want to create json format it had to be in this format for it to read:
[
{
"":"",
"":[
{
"":"",
"":""
}
]
}
]

PHP array key is NULL, array appears empty

I'm rather new to PHP and I am kind of stuck here writing this simple script; what I am trying to ultimately do is go through the content of a string and find the positions of all the occurrences I have listed in my $definitions array then map those positions in a separate array and return it...
rather simple but I am not sure where the problem arises, when i print_r on the array in different parts of code, thinking its a scope issue, I keep seeing that the key value of the array is NULL and also when I try and access a value of the array I am sure exists for a given key, i also get nothing; any help would be appreciated...
thank you!
<?php
class html2DokuWiki {
function definition_map($content){
$definitions = array("<title" => " ","<h" => array("=", 6),"<p" => "\n\n","<b" => "**","<strong" => "**","<em" => "//","<u" => "__","<img" => " ","<a" => " ","<ul" => " ","<ol" => "*","<li" => "-","<dl" => " ","<dt" => " ","<dd" => " ");
$element_pos = array();
foreach($definitions as $html_element){
$offset = 0;
$counter = 0;
$element_pos[(string)$html_element] = array(); //ask phil why do i need to cast in order to use the object?
while($offset = strpos($content, $html_element, $offset + 1)){
$element_pos[(string)$html_element][] = $offset;
};
};
//print_r($element_pos);
echo $element_pos["<p"][0];
return $element_pos;}
function run($page){
return $this->definition_map($page);}
};
$debug = new html2DokuWiki();
$url = "http://www.unixwiz.net/techtips/sql-injection.html";
$content = file_get_contents($url);
//echo $content;
//print_r($debug->run($content));
$test = $debug->run($content);
echo "<p> THIS:".$test["<p"][0]."</p>";
//print_r($test);
?>
If it's the key you want to use as $html_element as an index you should do:
foreach($definitions as $html_element => $value){

Categories