For anyone familiar with the Camfind API, I've got a bit of a stumper today Implementing the API in PHP. I've followed the instructions as best I could, and I'm getting the proper token back for my first call. I'm then appending the token to the URL, removing the form data, and keeping the json header, as well as the header with my key. Whatever I try, however, returns: array(1) { ["status"]=> string(13) "not completed" }
Here's my code:
<?php
///////////////////////////////////
// FIRST REQUEST
///////////////////////////////////
//set POST variables
$url = 'https://camfind.p.mashape.com/image_requests';
$fields = array(
"image_request[altitude]" => "27.912109375",
"image_request[language]" => "en",
"image_request[latitude]" => "35.8714220766008",
"image_request[locale]" => "en_US",
"image_request[longitude]" => "14.3583203002251",
"image_request[remote_image_url]" => "https://www.google.com/images/srpr/logo11w.png"
);
$headers = array(
'X-Mashape-Key: I-put-my-real-key-here',
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json'
);
//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_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
$result = json_decode($result, true);
///////////////////////////////////
// SECOND REQUEST
///////////////////////////////////
//set POST variables
$url = "https://camfind.p.mashape.com/image_responses/" . $result['token'];
echo $url;
$headers = array(
'X-Mashape-Key: I-put-my-real-key-here',
'Accept: application/json'
);
//open connection
$ch = curl_init();
//set the url
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
var_dump(json_decode($result, true));
Help appreciated!
Camfind support just got back to me, and made the following suggestion "Hi, it takes around 10-15 seconds for the image recognition to occur. Build in a loop with a delay before making the second call with the token, or try calling again and use a timer to re-call if not completed is still returned until it changes status to completed."
With this advice, I've updated my code as follows:
I added:
$start = microtime(true);
To the top of my file. I then wrapped my second curl call like so:
do {
//set the url
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_LOW_SPEED_TIME, 30);
$result = json_decode(curl_exec($ch), true);
} while((number_format((microtime(true) - $start), 2) < 20) && $result['status'] == 'not completed');
This is the solution, and the search now executes correctly.
Related
I am writing a code in PHP where i need to call and API (Sending username and password) and then fetch the authorization value.
I tried some solutions which are already there on stack but was not able to do the same
Can anyone please suggest a way around
This is one of the code i tried
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "HandleHeaderLine");
$output = curl_exec($ch);
curl_setopt($ch, CURLOPT_HEADERFUNCTION,
function($curl, $header) use (&$headers)
{
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) // ignore invalid headers
return $len;
$headers[strtolower(trim($header[0]))][] = trim($header[1]);
return $len;
}
);
You call your API before add the headers:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$headers = array(
"X-Custom-Header: value",
"X-Custom-Header: value"
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($ch); //Call your api at end
I was able to read the headers, I was trying to read the http header responses from https url posting request to http API
I am using below given code for getting the flight results from Skyscanner API from CURL using ajax in cakephp 3
and I am executing it in loop if there is more than one location's flight searched by user , so the problem is its not always returning all the flight result everytime until I refresh the page and when I refresh another ajax request calls with the same parameter and than I am getting all the results, I dont know why its not fetching all the result in first time please suggest me the best solution for this ,Thanks all for the help
$apiParamsUrl = "http://www.skyscanneraffiliate.net/portal/en-GB/UK/LivePricing/TestHarness?apikey=*******&country=GB¤cy=GBP&locale=en-GB&originplace=".$origin."&destinationplace=".$destination."&outbounddate=".$routes['date']['start_date']."&adults=".$routes['no_of_traveller']['no_of_traveller']."&children=0&infants=0&locationschema=iata&cabinclass=economy&groupPricing=true";
$apiParamsStr = parse_url($apiParamsUrl, PHP_URL_QUERY);
parse_str($apiParamsStr, $apiParamsArray);
$apiSessionUrl = 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $apiSessionUrl);
curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Accept: application/json'));
curl_setopt($ch,CURLOPT_POST, count($apiParamsArray));
curl_setopt($ch,CURLOPT_POSTFIELDS, $apiParamsStr);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch,CURLOPT_VERBOSE, 1);
curl_setopt($ch,CURLOPT_HEADER, 1);
if(!curl_exec($ch)){
break;
}
$response = curl_exec($ch);
$header_size = curl_getinfo($ch,CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
curl_close($ch);
preg_match('~Location: ([^\s]+)~', $header, $matches);
Try following code, I've changed it a little bit:
$apiParamsUrl = "http://www.skyscanneraffiliate.net/portal/en-GB/UK/LivePricing/TestHarness?apikey=*******&country=GB¤cy=GBP&locale=en-GB&originplace=" . $origin . "&destinationplace=" . $destination . "&outbounddate=" . $routes['date']['start_date'] . "&adults=" . $routes['no_of_traveller']['no_of_traveller'] . "&children=0&infants=0&locationschema=iata&cabinclass=economy&groupPricing=true";
$apiParamsStr = parse_url($apiParamsUrl, PHP_URL_QUERY);
parse_str($apiParamsStr, $apiParamsArray);
$apiSessionUrl = 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiSessionUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Accept: application/json'));
curl_setopt($ch, CURLOPT_POST, true); // <-- changed
curl_setopt($ch, CURLOPT_POSTFIELDS, $apiParamsStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 0); // <-- changed
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // <-- added
$body = curl_exec($ch);
if (false === $body) {
break;
}
curl_close($ch);
var_export($body);
I having issues running the correct cURL request. I am meant to do a Post request to the URL.
The example only runs a command line cURL request
$ curl -i -X POST {URL}
The issue I am running the following code and I am getting '400 Bad Request'
$ch = curl_init();
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_TIMEOUT, 10 );
$output = curl_exec( $ch );
curl_close( $ch );
Can anyone help with sending the request correctly.
You're missing the CURLOPT_POSTFIELDS you wanna get by the request.
As explained here you're gonna need to set those fields:
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
?>
Try this:
POST Function:
function httpPost($url,$params)
{
$postData = '';
//create name value pairs seperated by &
foreach($params as $k => $v)
{
$postData .= $k . '='.$v.'&';
}
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;
}
Calling the Function:
$params = array(
"name" => "Ravishanker Kusuma",
"age" => "32",
"location" => "India"
);
echo httpPost("http://hayageek.com/examples/php/curl-examples/post.php",$params);
See, if that helps. Ref: link
curl_setopt( $ch, CURLOPT_POST, TRUE );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $array );
Check the manual
To post, just make use of following curl options and try.
(if your url is - "https") {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //if required.
curl_setopt($ch, CURLOPT_URL, );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
return curl_exec($ch);
I guess the url you are passing doesn't have post fields. eiter you can make use of CURLOPT_POSTFIELDS and your post params their or else attache it to the url using http_build_query(post params)
http://www.url.com?arg1=val1&arg2=val2
Also after spending 5 hours at same code i just found the solution of my problem
If you are using Array in post Fields you have to json_encode that array to recognize as POST parameters
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($fields));
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($curl);
So This is Working CURL Code WITH POST Request
Give a Rep+ If my
i'm trying using cURL for a GET request like this:
function connect($id_user){
$ch = curl_init();
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);
curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
$body = '{}';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$authToken = curl_exec($ch);
return $authToken;
}
As you an see i want to pass $body as the request's body , but i don't know if its correct or not and i can't debug this actually, do you know if is the right to use curl_setopt($ch, CURLOPT_POSTFIELDS,$body); with a GET request?
Cause this enteire code works perfect with POST, now i'm trying change this to GET as you can see
The accepted answer is wrong. GET requests can indeed contain a body. This is the solution implemented by WordPress, as an example:
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );
EDIT: To clarify, the initial curl_setopt is necessary in this instance, because libcurl will default the HTTP method to POST when using CURLOPT_POSTFIELDS (see documentation).
CURLOPT_POSTFIELDS as the name suggests, is for the body (payload) of a POST request. For GET requests, the payload is part of the URL in the form of a query string.
In your case, you need to construct the URL with the arguments you need to send (if any), and remove the other options to cURL.
curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
//$body = '{}';
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
//curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
<?php
$post = ['batch_id'=> "2"];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://example.com/student_list.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
$result = json_decode($response);
curl_close($ch); // Close the connection
$new= $result->status;
if( $new =="1")
{
echo "<script>alert('Student list')</script>";
}
else
{
echo "<script>alert('Not Removed')</script>";
}
?>
For those coming to this with similar problems, this request library allows you to make external http requests seemlessly within your php application. Simplified GET, POST, PATCH, DELETE and PUT requests.
A sample request would be as below
use Libraries\Request;
$data = [
'samplekey' => 'value',
'otherkey' => 'othervalue'
];
$headers = [
'Content-Type' => 'application/json',
'Content-Length' => sizeof($data)
];
$response = Request::post('https://example.com', $data, $headers);
// the $response variable contains response from the request
Documentation for the same can be found in the project's README.md
you have done it the correct way using
curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
but i notice your missing
curl_setopt($ch, CURLOPT_POST,1);
I have the following php code
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_USERAGENT, $this->_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->_headers);
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->_cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->_cookie_file_path);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}');
curl_setopt($ch, CURLOPT_POST, 1);
But I don't understand why is not working . The API that I'm posting the JSON to says that the parameters were not received . Is there anything wrong in my code ? I think the whole trick is on the JSON parameters... I'm not sure how to send them as I couldn't see any "nave->value" pair with the http analyzer as it usually appears in simple forms ... just that JSON code without any "name".
You can try as follows.
Basically if we have a array of data then it should be json encoded using php json_encode. And you should also add content-type in header which can be defined in curl as curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$data = array("country"=>"US","states"=>array("MHASASAS"=>"MH","XYZABABA"=>"XYZ"));
$postdata = json_encode($data);
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
you can use this and replace with
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}');
use this
$Parameters = array(
'MerchantCode' => $MerchantCode,
'PriceValue' => $amount,
'ReturnUrl' => $callback,
'InvoiceNumber' => $resnum,
);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($Parameters));
If:you use post method,you should know that:
CURLOPT_POST TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
#see http://php.net/manual/en/function.curl-setopt.php
So:you can do like this:
$ar_form = array('name'=>'PHPJungle','age'=>66,'gender'=>'male');
$poststr = http_build_query($ar_form ); # important
$options[CURLOPT_HTTPGET] = false;
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = $poststr ; //default type:application/x-www-from-urlencoded
curl_setopt_array ( $ch, $options );
# #todo your other codes
This is my class I have used for a long time.The class is based on PHP cURL.
It supports GET/POST,HTTP/HTTPS.
#see https://github.com/phpjungle/iHttp/
You can post a json data with curl like so:
Using Command Prompt:
curl -X POST -H "Content-Type: application/json" -d '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}' $url
Using PHP:
$data = array("folderId"=>"1","parameters"=>array("amount"=>3,"ascending"=>false,"offset"=>0,"sort"=>"date"));
$postdata = json_encode($data);
OR
$postdata = '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
You haven't set the content type, so the post data is being sent as form data. Try setting the content type to application/json.
If that doesn't work, try wrapping the json string with an array.
$link = "http://test.domain/myquery";
$json = '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}';
$postdata = json_decode($json);
echo openurl($link, $postdata);
This works as json decode converts a json string into array.
function openurl($url, $postvars = "") {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
return $content;
}
if your API endpoint using body for send request using json data may be you can use Guzzle the doc is here doc.
use GuzzleHttp\Client;
$client = new Client();
$request = $this->client->post($url,array(
'content-type' => 'application/json'
),array());
$request->setBody($json_data);
$response = $request->send();
return $response;
hope this work.
You can do it make by steps:
$data = array(
'folderId'=>"1","parameters"=>array(
"amount"=>"3","ascending"=>false,"offset"=>0,"sort"=>"date"
)
);
$data_string = http_build_query($data);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result,true);
I don't know if you need the header. I think that by default it is already application/x-www-form-urlencode
If it doesn't work, try changing the $data values in array. Think it helps. :)
I'm not sure, that this is the solution but this works for me when posting json, change the json from
'{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}'
to
"{'folderId':'1','parameters':{'amount':3,'ascending':false,'offset':0,'sort':'date'}}"
The only change i made was the double quotes are now on the outside, that works for me but I'm obviously posting to a different server
Only other help I could offer is to download a network debugging tool such as Fiddler or Charles proxy and monitor the requests sent/received, it could be a case that something else is wrong in your code.
Hope i helped :)
first of all
please check the curl http status code
$http_code= curl_get_info($exec_res,CURL_HTTP_CODE);
then modify this request header set with post header API server add a recorder to log those request info.