I've made a CURL request but its not working - php

Below is my CURL request. Im trying to pull data from a CRM called pipedrive. The URL is pulling the data correctly but for some reason its not displaying on my website.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.pipedrive.com/v1/persons/find?term=devonvermaak2%40gmail.com&start=0&search_by_email=1&api_token=e7f91c84dad486160a9744f4972d7f742de3d",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-length": "217",
"content-type": "application/json",
"x-ratelimit-limit": "20",
"x-ratelimit-remaining": "19",
"x-ratelimit-reset": "2"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
//because of true, it's in an array
$response = json_decode($response, true);
echo 'Name: '. $response['data']['name']. '<br />';
echo 'Email: '. $response['data']['email']. '<br />';
echo 'Phone: '. $response['data']['phone'];
Its not showing the data at all. Is there something wrong with my code?
Note: I've edited the api token for security purposes..

since your $response is
{
"success": true,
"data": [
{
"id": 91235,
"name": "Devon Vermaak",
"email": "devonvermaak2#gmail.com",
"phone": "0555877857",
"org_id": null,
"org_name": "",
"visible_to": "3"
}
],
"additional_data": {
"search_method": "search_by_email",
"pagination": {
"start": 0,
"limit": 100,
"more_items_in_collection": false
}
}
}
you can see that the data is an array
hence, you can access the values via its index. Ex
$response['data'][0]['name'] returns Devon Vermaak
echo 'Name: '. $response['data'][0]['name']. '<br />';
echo 'Email: '. $response['data'][0]['email']. '<br />';
echo 'Phone: '. $response['data'][0]['phone'];

Wrong 'CURLOPT_HTTPHEADER' array values.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.pipedrive.com/v1/persons/find?term=devonvermaak2%40gmail.com&start=0&search_by_email=1&api_token=e7f91c84dad486160a9744f4972d7f742de3d",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control"=> "no-cache",
"content-length"=> "217",
"content-type"=> "application/json",
"x-ratelimit-limit"=> "20",
"x-ratelimit-remaining"=> "19",
"x-ratelimit-reset"=> "2"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
//because of true, it's in an array
$response = json_decode($response, true);
print_r($response);

Related

How to Combine two api calls and make a loop using php

I am trying to loop an array of fixtures using foreach and this works fine. However I want to pick the {fixtuteID} from the fixtures loop and put it in the predictions api endpoint
Api call for fixtures
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api-football-v1.p.rapidapi.com/v3/fixtures?date=2xx1-06-10&timezone=XXXXX",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'x-rapidapi-key: XxXxXxXxXxXxXxXxXxXxXxXx',
'x-rapidapi-host: xvvvxxx.io'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Api call for predictions which requires {fixtuteID} from the above
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api-football-v1.p.rapidapi.com/v3/predictions?fixture={fixtuteID}",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'x-rapidapi-key: XxXxXxXxXxXxXxXxXxXxXxXx',
'x-rapidapi-host: xvvvxxx.io'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Below is the loop I would like.
fixture 1 and prediction-fixture 1
fixture 2 and prediction-fixture 2
fixture 3 and prediction-fixture 3
fixture 4 and prediction-fixture 4
end loop
EDIT: my loop
$fixture = curl_exec($curl);
$fs = json_decode($fixture, true);
$fixtures = $fs['response'];
//get error
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
foreach($fixtures as $fx){
//fixture ID {fixtuteID}
echo $fx['fixture']['id'];
//I wand to add the prediction here like this-- echo $pr['prediction']."<br>";
}
}
And that loop gives me
fixture 1
fixture 2
fixture 3
fixture 4
EDIT I want to get the
"predictions->winner->id": 2232,->name": "Sao Jose",->comment": "Win or draw"
},
The json response from the predictions call is as below.
{
"get": "predictions",
"parameters": {
"fixture": "840715"
},
"errors": [
],
"results": 1,
"paging": {
"current": 1,
"total": 1
},
"response": [
{
"predictions": {
"winner": {
"id": 2232,
"name": "Sao Jose",
"comment": "Win or draw"
},
"win_or_draw": true,
"under_over": null,
"goals": {
"home": "-2.5",
"away": "-1.5"
},
"advice": "Double chance : Sao Jose or draw",
"percent": {
"home": "50%",
"draw": "50%",
"away": "0%"
}
},
"league": {
"id": 75,
"name": "Serie C",
"country": "Brazil",
"logo": "https://media.api-sports.io/football/leagues/75.png",
"flag": "https://media.api-sports.io/flags/br.svg",
"season": 2022
},
where I want to pick predictions -> winner -> id for each fixture in the loop.
It's not entirely clear where you got stuck with this, but it seems like the neatest way would be to put the cURL code in a function and then call the function from the loop. (Of course you could put the cURL code directly in the looop but it would clutter it up a bit.)
foreach($fixtures as $fx)
{
//fixture ID
echo $fx['fixture']['id'];
echo getPrediction($fx["fixture"]["id"])."<br>";
}
function getPrediction($fixtureID)
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api-football-v1.p.rapidapi.com/v3/predictions?fixture=
$fixtureID",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'x-rapidapi-key: XxXxXxXxXxXxXxXxXxXxXxXx',
'x-rapidapi-host: xvvvxxx.io'
),
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}

Curl iteratively pass multiple payloads from json or array

How do I pass multidimensional associative array or a json as a payload to cURL request. I have been trying to wrap my head around this for sometime now without any success.
Here is what I have done so far. I make a curl request and pass a json to the CURLOPT_POSTFIELDS fields. This works alright. The problem is I want the code to run for multiple users which are in a json string saved in a variable
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://test.url/tokens',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"customerName": "orland",
"mno": "Network",
"amount": "1",
"msisdn": "447911123456",
"description": "Awaiting",
"reference": "0fgdufgdfgdfs"
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
The above code works fine.
But the payload for CURLOPT_POSTFIELDS is not fixed.
So this is what I tried doing, I encoded the json string and tried passing it to a for loop. I am sure the approach isn't bad, but I am not getting the syntax quite right. Here is my code.
<?php
$recip = '[{
"customerName": "Sorland",
"mno": "Network",
"amount": "1",
"msisdn": "447911123346",
"description": "Awaiting",
"reference": "0fgdufgdfgdfs"
},
{
"customerName": "Corland",
"mno": "MTN",
"amount": 1,
"msisdn": "447911123678",
"description": "Awaiting",
"reference": "0jsbfbsubfhbj"
},
{
"customerName": "orland",
"mno": "MTN",
"amount": 1,
"msisdn": "447911123111",
"description": "Awaiting",
"reference": "1234568djnfjnfjds"
}]';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://test.url.com/api/',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>
echo ("'{<br>");
foreach($arr[$keys[$i]] as $key => $value) {
echo implode($key . " : " . $value . ",<br>");
}
echo "}',<br>";
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
}
I want to use a for loop to make multiple curl request with different payloads, and the payloads are coming from the json data above. I converted the json to an array to be able to loop through and converted it back to a json for CURLOPT_POSTFIELDS.
This seems a simpler way to make multiple call to curl and save the responses, hope I got the right end of the stick this time :)
$recip =
'[
{"customerName": "Sorland", "mno": "Network", "amount": "1",
"msisdn": "447911123346","description": "Awaiting","reference": "0fgdufgdfgdfs"
},
{"customerName": "Corland","mno": "MTN","amount": 1,
"msisdn": "447911123678","description": "Awaiting","reference": "0jsbfbsubfhbj"
},
{"customerName": "orland","mno": "MTN","amount": 1,"msisdn": "447911123111",
"description": "Awaiting","reference": "1234568djnfjnfjds"
}
]';
// make a PHP datatype out of the JSON so you can use it
$recipients = json_decode($recip);
$responses = [];
foreach ( $recipients as $r) {
$curl = curl_init();
// convert $r back to json so it can be passed as param
$postfield = json_encode($r);
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://test.url.com/api/',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $postfield,
CURLOPT_HTTPHEADER => array('Content-Type: application/json')
));
$response[] = curl_exec($curl);
// if you need to know which customer the response was for
// use this next line instead, for example
//$response[$r->customerName] = curl_exec($curl);
curl_close($curl);
}
// this is now an array of all responses
print_r($responses);

Cant Extract data from PHP curl response

I learning to use API from: https://rapidapi.com/lambda/api/face-recognition-and-face-detection/endpoints
I want to save or echo albumkey to variable and store in database. I have tried $response->albumkey and didn't work.
here my response below:
{
album: "amanda11",
msg: "Please put this in a safe place and remember it, you'll need it!",
albumkey: "c00bc5d3b1bf64a1ba68f690d4dabee494a2c6fbf48cf8f09c6d41fbece45b7b"
}
And here my code:
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://lambda-face-recognition.p.rapidapi.com/album",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "album=amanda11",
CURLOPT_HTTPHEADER => [
"content-type: application/x-www-form-urlencoded",
"x-rapidapi-host: lambda-face-recognition.p.rapidapi.com",
"x-rapidapi-key: 932571abf0msh45cf0f3cef74aacp19e151jsn33e9949a1974"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
if ($err) {
echo $err;
} else {
echo $response;
}
You need to parse the JSON before you can access its values. In PHP you do that with json_decode():
$response = curl_exec($curl);
$err = curl_error($curl);
if ($err) {
echo $err;
} else {
$json = json_decode($response);
echo $json->albumkey ;
}
Here's a basic example:
$response = '{
"album": "amanda11",
"msg": "Please put this in a safe place and remember it, you\'ll need it!",
"albumkey": "c00bc5d3b1bf64a1ba68f690d4dabee494a2c6fbf48cf8f09c6d41fbece45b7b"
}';
$json = json_decode($response);
echo $json->albumkey;
Demo

PHP safe-browsing return empty string

this PHP file is for knowing if a site is a safe or not thanks to safe-browsing.
$curl = curl_init();
$certificate="C:\cacert.pem";
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://safebrowsing.googleapis.com/v4/threatMatches:find?key= [API_KEY]',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_CAINFO => $certificate,
CURLOPT_CAPATH => $certificate,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => " {
'client': {
'clientId': 'nameclient',
'clientVersion': '1.0.0'
},
'threatInfo': {
'threatTypes': ['MALWARE', 'SOCIAL_ENGINEERING'],
'platformTypes': ['WINDOWS'],
'threatEntryTypes': ['URL'],
'threatEntries': [
{'url': 'http://www.yoytube.com/'}
]
}
}",
CURLOPT_HTTPHEADER => array(
'content-type: application/json'
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The output should be similar to this response body
{
"matches": [
{
"threatType": "MALWARE",
"platformType": "WINDOWS",
"threatEntryType": "URL",
"threat": {
"url": "http://www.example.org/"
},
"threatEntryMetadata": {
"entries": [{
"key": "malware_threat_type",
"value": "landing"
}]
},
"cacheDuration": "300.000s"
}
}]
}
but currently my output is {}
At start i have tried to pass this url
https://sb-ssl.google.com/safebrowsing/api/lookup?client=' . CLIENT . '&apikey=' . API_KEY . '&appver=' . APP_VER . '&pver=' . PROTOCOL_VER . '&url=' . $urlToCheck
at curl_init(), but in this case the status returned was 0

Downloading & Uploading a file with cURL

I have been trying to use cURL to interact with an api, I want to download a file with this snippet but all it does is open up the file in the browser and the second snippet is supposed to upload a pdf file along with multipart form data with cURL, but all it give me is;
"{"type":"request_error","detail":"Multipart form parse error - Invalid boundary in multipart: None"}"
error, I have already tried to execute the thing with postman, it runs fine there and when i copy and paste the same code it still gives me the same errors as above, cheers, thanks in advance.
Here is the code;
Downloading Snippet
$id = "rZFbMKmj2zZbMUbp5KrjCH";
$auth = $this->access_token;
$curl = curl_init( PANDA_APIURL . "/documents/".$id."/download");
//$fp = fopen('Test.pdf', 'w+');
curl_setopt_array($curl, array(
CURLOPT_URL => PANDA_APIURL . "/documents/".$id."/download",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 50,
CURLOPT_TIMEOUT => 300,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//CURLOPT_FILE => $fp,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer $auth"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
//fclose($fp);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Uploading the file with multipart form data snippet;
$auth = $this->access_token;
$boundary = '7aBMjcE3CIYntqQ3';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => PANDA_APIURL . "/documents",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => '------WebKitFormBoundary7aBMjcE3CIYntqQ3
Content-Disposition: form-data; name="file"; filename="samplepdf.pdf"
Content-Type: application/pdf
------WebKitFormBoundary7aBMjcE3CIYntqQ3
Content-Disposition: form-data; name="data"
{
"name": "Pdf Doc",
"recipients": [
{
"email": "xyz#gmail.com",
"first_name": "Jane",
"last_name": "Roe"
}
],
"fields": {
"name": {
"value": "John"
},
"like": {
"value": true
}
}
}
------WebKitFormBoundary7aBMjcE3CIYntqQ3',
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer $auth",
"Content-Type: multipart/form-data;----WebKitFormBoundary'.$boundary"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

Categories