How do I use arrays in cURL POST requests - php

I am wondering how do I make this code support arrays? At the moment the images array only seems to send the first value.
Here is my code:
<?php
//extract data from the post
extract($_POST);
//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
'username' => "annonymous",
'api_key' => urlencode("1234"),
'images[]' => urlencode(base64_encode('image1')),
'images[]' => urlencode(base64_encode('image2'))
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
?>
and this is what is received at the api
VAR: username = annonymous
VAR: api_key = 1234
VAR: images = Array
array(3) {
["username"]=> string(10) "annonymous"
["api_key"]=> string(4) "1234"
["images"]=> array(1) { // this should contain 2 strings :( what is happening?
[0]=> string(8) "aW1hZ2Uy"
}
}
What is happening to the second value in images[]?

You are just creating your array incorrectly. You could use http_build_query:
$fields = array(
'username' => "annonymous",
'api_key' => urlencode("1234"),
'images' => array(
urlencode(base64_encode('image1')),
urlencode(base64_encode('image2'))
)
);
$fields_string = http_build_query($fields);
So, the entire code that you could use would be:
<?php
//extract data from the post
extract($_POST);
//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
'username' => "annonymous",
'api_key' => urlencode("1234"),
'images' => array(
urlencode(base64_encode('image1')),
urlencode(base64_encode('image2'))
)
);
//url-ify the data for the POST
$fields_string = http_build_query($fields);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
?>

$ch = curl_init();
$data = array(
'client_id' => 'xx',
'client_secret' => 'xx',
'redirect_uri' => $x,
'grant_type' => 'xxx',
'code' => $xx,
);
$data = http_build_query($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, "https://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);

Related

get data with CURL and JSON

i am trying to get data using Curl
i was trying to get best result but i got
but my goal to get specific line NOT all the lines.
see my code and please help to get the result with
"routing" AND "tot_dist" Other variables NO
here is my code
<?php
function httpPost($url,$params)
{
$postData = '';
//create name value pairs seperated by &
foreach($params as $l => $v)
{
$postData .= $l . '='.$v.'&';
}
$postData = rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}
$params = array(
"id1" => "OOMS",
"id2" => "OOSA",
"routing" => "",
"dbid" => "2006",
"k" => "",
);
echo httpPost("http://rfinder.asalink.net/free/autoroute_rtx.php",$params);
// I WANT TO GET THE RESULT WITH ROUTING AND tot_dist ONLY LIKE THIS
//OOMS DCT KASIN DCT OOSA
//459.5
?>
This result i got
{"rc":"100","rmsg":"OK","gc_dist":459.2,"routing":"OOMS DCT KASIN DCT OOSA","tot_dist":459.5,"legs":[{"wt":"A","id":"OOMS","lat":"23.6002","lon":"58.2836","freq":"","via":"","brg":"0.0","dist":"0.0","name":"MUSCAT INTERNATIONAL"},{"wt":"W","id":"KASIN","lat":"20.3147","lon":"55.9617","freq":"","via":"DCT","brg":"214.7","dist":"235.8","name":"KASIN"},{"wt":"A","id":"OOSA","lat":"17.0387","lon":"54.0913","freq":"","via":"DCT","brg":"209.6","dist":"223.6","name":"SALALAH"}]}
but i need only "Routing" and "tot_dist"
Once you make a request, you will get all the data. You can then select what you need. Here is what your code should look like to select only routing and tot_dist
function httpPost($url,$params)
{
$postData = '';
//create name value pairs seperated by &
foreach($params as $l => $v)
{
$postData .= $l . '='.$v.'&';
}
$postData = rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt(
$ch, CURLOPT_HTTPHEADER,
array(
'Accept:application/json'
)
);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return json_decode($output,true);
}
$params = array(
"id1" => "OOMS",
"id2" => "OOSA",
"routing" => "",
"dbid" => "2006",
"k" => "",
);
$data = httpPost("http://rfinder.asalink.net/free/autoroute_rtx.php",$params);
echo $data['routing'] . "\n";
echo $data['tot_dist'] . "\n";

consume Restful service in php?

I am trying to consume a Restful service using the below code:
$dat=array(
'entidad' => "F001",'tipoIdentificacion' => 'CC','numeroIdentificacion' => '1020442757'
);
$postdata =http_build_query( $dat );
//print_r($postdata);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
//var_dump($context);
$result=file_get_contents('http://172.18.131.195:9090/lince/rest/pazysalvo1/avaldescfin',FILE_USE_INCLUDE_PATH, $context);
//echo $result;
//$result = json_decode(file_get_contents('http://172.18.131.195:9090/lince/rest/pazysalvo1/avaldescfin?', false, $context),true);
print_r($result);
But it does not recognize the parameters that I am sending, and therefore returns null values:
{"entidad":"F001","tipoIdentificacion":null,"numeroIdentificacion":null,"codPersona":0,"estadoConsulta":"1","avales":[]}
How should I send the parameters?
I couldn't do it in this Asian way that I gave a solution in this other way.
//set POST variables
$url = 'http://172.18.131.195:9090/lince/rest/pazysalvo1/avaldescfin';
$fields = array(
'entidad' => 'F001','tipoIdentificacion' =>$tipoid,'numeroIdentificacion' => $numid
);
//url-ify the data for the POST
foreach($fields as $key=>$value)
{
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
$result=json_decode($result,true);
/*echo "<pre>";
print_r($result);
echo "</pre>";*/

Unable to perform a POST request in php using cURL

I am unable to perform a POST request in php, the following is my code:
$ch = curl_init();
$fields = "=var1?var2?var3";
$url = "http://localhost/Profile.php?";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
$output = curl_exec($ch);
curl_close($ch);
profile.php:
print_r($_POST);
Nothing seems to be displaying on the page just an empty array, if I do via GET it works. What have I done wrong?
Your $fields string should be in the format "key1=value1&key2=value2...", without a prepended =. So, in your case:
$fields = "key1=var1&key2=var2&key3=var3";
Additionally, the print_r($_POST) command in your code will render what has been POSTed to your page, not by your page.
//set POST variables
$url = 'http://domain.com/get-post.php';
$fields = array(
'lname' => urlencode($last_name),
'fname' => urlencode($first_name),
'title' => urlencode($title),
'company' => urlencode($institution),
'age' => urlencode($age),
'email' => urlencode($email),
'phone' => urlencode($phone)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);

Posting data using Curl in XML Format

Currently post my data in HTTP Post format and i need to post it in XML and add the header.
This is how i currently post my data.
//extract data from the post
extract($_POST);
//set POST variables
$url = 'https://test.com/checklead';
$fields = array(
'surname' => urlencode($surname),
'first_name' => urlencode($first_name),
'dob' => urlencode($dob),
'email' => urlencode($email),
'home_phone' => urlencode($home_phone),
'mobile_phone' => urlencode($mobile_phone),
'work_phone' => urlencode($work_phone),
'postcode' => urlencode($postcode),
'leadid' => urlencode(123),
'affid' => urlencode(123),
'subid' => urlencode(123),
'bank_acno' => urlencode($bank_acno),
'bank_sort' => urlencode($bank_sort),
'amount_required' => urlencode($amount_required),
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
How do i post this in XML Format and add a Header : http://www.header.com
You've not set Content-Type.
Try something along the lines of :
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Header1: my_header_value'
));
$output = curl_exec($ch);
or you could look at using a library such as Guzzle which does a lot of the error handling etc for you.

Php : Curl unwanted output

I have Below Curl Code
<?php
$url = 'https://graph.facebook.com/me/events';
$fields = array(
'access_token' => $token,
'name' => 'Event name',
'description' => 'The Description ',
'start_time' => '2013-03-02'
);
foreach($fields as $key=>$value)
{
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
?>
In Above Code , I did not use echo $result , But its returning output as {"id":"209557021119579"}
Use this :
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
for return data instead of echoing data
you should use CURLOPT_RETURNTRANSFER ,
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Categories