CURL is not executing first time properly - php

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&currency=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&currency=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);

Related

PHP: curl script fails

The task seemed simple.
The login (email) used for authentication must be passed in the login request parameter. In the request body (Body), the user password is passed as a string encoded in UTF-8.
Example request:
POST /auth/authenticate-by-pass?login=testlogin#testDomain.net HTTP/1.1
Host: somehost.ru
Body: somepassword
Cache-Control: no-cache
If the request is successful, the response will contain a JSON object
Tried to do like this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://somehost.ru/auth/authenticate-by-pass?login=mylogin#mydomain.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_POSTFIELDS, "mypassword" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain', 'Host: somehost.ru'));
$result=curl_exec($ch);
$php_obj = json_decode($result, true);
print_r($php_obj);
No result. Nothing is displayed. Please help.
In my understanding what you need can be simply (please amend the headers to further suit your needs if necessary) :
$ch = curl_init();
$post = [
'password' => 'xxxxxx'
];
curl_setopt($ch, CURLOPT_URL, 'http://somehost.ru/auth/authenticate-by-pass?login=mylogin#mydomain.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
$php_obj = json_decode($result, true);
print_r($php_obj);
curl_close($ch);
Solved the problem. Ken Lee and everyone else thanks for the help.
$ch = curl_init();
$post = 'mypassword';
curl_setopt($ch, CURLOPT_URL, 'http://somehost.ru/auth/authenticate-by-pass?login=mylogin#mydomain.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
$php_obj = json_decode($result, true);
print_r($php_obj);
curl_close($ch);

Issue with Strava API

I am trying to get a list of my activities using cURL I can get the list of my clubs ok. Can't seem to figure out what I am doing wrong
I am having an issue when using the request. $ http GET "https://www.strava.com/api/v3/activities/{id}?include_all_efforts=" "Authorization: Bearer [[token]]"
I cam getting an error
string(95) "{"message":"Record Not Found","errors":
[{"resource":"Activity","field":"id","code":"invalid"}]}"
**I have tried the following**
$num = "2149016538";
$int = (int)$num;
// $url = 'https://www.strava.com/api/v3/athlete/clubs';
$url = 'https://www.strava.com/api/v3/activities/{'.$int.'}?include_all_efforts=true';
**No success**
**I have also tried this**
$num = "2149016538";
$int = (int)$num;
// $url = 'https://www.strava.com/api/v3/athlete/clubs';
$url = 'https://www.strava.com/api/v3/activities/?id='.$int.'?include_all_efforts=true';
$authorization = "Authorization: Bearer 23232323";
$num = "2149016538";
$int = (int)$num;
// $url = 'https://www.strava.com/api/v3/athlete/clubs';
$url = 'https://www.strava.com/api/v3/activities/{'.$int.'}?include_all_efforts=true';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
var_dump($result);
curl_close($ch);
json_decode($result);

php curl post json data contains a null entry for parameter

i've create a php function to make a post json data request using curl
My Code :
$url = 'http://77.42.154.142:90/home/test/GetNewCustomer';
$data = array("UpdatedOn" => "1/23/2004 1:00AM","CreatedOn" => "1/23/2015 1:00AM");
$fields = json_encode($data);
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'sduser: 34EE0A61-F3A5-4E21-86D3-C7B7DAF9C8F9913982A9-3025-4C37-8093-B664B9310F91',
'Content-Length:'.strlen($fields)
));
curl_setopt($post, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml; charset=utf-8', 'Content-Length: '.strlen($fields)));
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//curl_setopt($post, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($post);
// for debugging
var_dump(curl_getinfo($post), $result);
// if(false === $result) { // request failed
// die('Error: "' . curl_error($post) . '" - Code: ' . curl_errno($post));
// }
curl_close($post);
But i've got this response The parameters dictionary contains a null entry for parameter
Any Suggestion ?

Camfind API issue in PHP

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.

PHP JSON GCM request from PHP

For days I tried to implement a number of solutions from the gcm & php thread here to get my server to send a message to the GCM server and then to my Android device. My call to curl_exec($ch) kept returning false. After a few days of racking my brain, reading and searching the web it seems I finally figured it out. I had to use GET instead of POST, I found that here, and I had to NOT verify the SSL. (I can't remember where I found that...)
I hope this helps someone who's having the same problem. And please, if anyone can improve upon this their corrections are more then welcome.
This is what was suggested by the thread linked to above:
$ch = curl_init();
// WRITE MESSAGE TO SEND TO JSON OBJECT
$message = '{"data":{"message":"here is the message","title":"message title"},"registration_ids":["'. $reg . '","'. $reg2 . '"]}';
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_URL, $gcmurl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// WRITE JSON HEADERS
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization:key=' . $apiKey)
);
$result = curl_exec($ch);
if(!$result > 0){
echo "<p>An error has occurred.<p>";
echo "<p>ERROR: $curl_error</p>";
}
else{
$json_return = json_decode($result);
echo var_dump($json_return);
$info = curl_getinfo($ch);;
echo "<p>httpcode: " . $info['http_code'] . "</p>";
}
curl_close($ch);
For me to get this working I have to implement the following.
$ch = curl_init();
$message = '{"data":{"message":"here is the message","title":"message title"},"registration_ids":["'. $reg . '","'. $reg2 . '"]}';
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_URL, $gcmurl);
/*
* COMMENT OUT THE FOLLOWING LINE
*/
*//curl_setopt($ch, CURLOPT_POST, true);*
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// WRITE JSON HEADERS
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization:key=' . $apiKey)
);
/*
* ADD THESE 2 LINES
*/
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch);
if(!$result > 0){
echo "<p>An error has occurred.<p>";
echo "<p>ERROR: $curl_error";
}
else{
$json_return = json_decode($result);
echo var_dump($json_return);
$info = curl_getinfo($ch);;
}
curl_close($ch);
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);
$data = json_encode($input);//Your json data...
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
switch($method)
{
case 'GET':
curl_setopt($handle,CURLOPT_HTTPGET,true);
break;
case 'POST':
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
break;
case 'PUT':
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
break;
case 'DELETE':
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
case 'FILE':
curl_setopt($handle, CURLOPT_HEADER, 0);
curl_setopt($handle, CURLOPT_VERBOSE, 1);
curl_setopt($handle, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($handle, CURLOPT_POST, true);
echo $data;
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
break;
}
$response = curl_exec($handle);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
return $response;
Have you uncommentted ;extension=php_curl.dll in your php.ini(remote or localhost)
This worked for me cause it returns :
{"multicast_id":8298406095978893272,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1439084688510033%9bd2607ff9fd7ecd"}]}
but I can't receive the notification on the client side.
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
require_once __DIR__ . '/db_config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
// $fields = array(
// 'registration_ids' => $registatoin_ids,
// 'data' => $message,
// );
$fields = '{"to":"caFPICUdKKM:APA91bEJW2vtQHy5IQcOM88WlT5zazf-D9LExvOaSGgAOHqSkHBeHWP34KV1BEKLA9n932BrZXTCwJajug4kcX2LrURY1NJPb9V-vmis1Ra8bo2Zw2BgIIXrfoDbM42Ip6RN_ic1C6eU","data":{"title":"Testing","body":"Success","icon":"R.mipmap.ic_launcher"}}';
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// 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, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>

Categories