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 .= '&';
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
I have seen a bunch of ways, but none that seem to work. My array data is coming back like this.
Array
(
[0] => RESULT=0
[1] => RESPMSG=Approved
[2] => SECURETOKEN=8cpcwfZhaH02qNlIoFEGZ1wO4
[3] => SECURETOKENID=253cad735251571cebcea28e877f4fd7
I use this:
<?php echo $response[2];?>
too get each out, that works. But I need to remove “SECURETOKEN=” so im left with just the number strings. I have been trying something like this with out success.
function test($response){
$secure_token = $response[1];
$secure_token = substr($secure_token, -25);
return $secure_token;
}
Also Im putting end number into a form input “Value” field. Not that that matters, unless it does?
Thanks
This is what I would do:
$keyResponse = [];
foreach ($response as $item) {
list($k, $v) = explode('=', $item, 2);
$keyResponse[$k] = $v;
}
Now you can easily access just the value part of each item based on the name:
echo $keyResponse['SECURETOKEN']; // output: 8cpcwfZhaH02qNlIoFEGZ1wO4
The advantage to this method is the code still works if the order of the items in $response changes
I get your secure token like this (tested):
<?php
$arr = array(
'RESULT=0',
'RESPMSG=Approved',
'SECURETOKEN=8cpcwfZhaH02qNlIoFEGZ1wO4',
'SECURETOKENID=253cad735251571cebcea28e877f4fd7'
);
$el = $arr[2];
$parts = explode('=', $el);
echo '#1 SECURETOKEN is ' . $parts[1];
// This break just for testing
echo '<br />';
// If you wanted to, you could revise the whole array
$new = array();
foreach( $arr as $el ){
$parts = explode('=', $el);
$new[$parts[0]] = $parts[1];
}
// Which would mean you could then get your securetoken like this:
echo '#2 SECURETOKEN is ' . $new['SECURETOKEN'];
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";
}
?>
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:
[
{
"":"",
"":[
{
"":"",
"":""
}
]
}
]
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){
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 .= '&';
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
)