Undefined index on cURL request on Graph API - php

I'm using Facebook's graph API to retrieve some data via a cURL call in PHP and I'm receiving an Undefined index error and I don't know how to target it correctly.
cURL Request:
<?php
/* Call the cURL request to pull in Instagram images */
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, "https://graph.facebook.com/v5.0/". get_option('insta_id') ."/media?fields=media_url,permalink,username,media_type,thumbnail_url&access_token=". get_option('insta_accesstoken'));
$result = curl_exec($curl);
$array = json_decode($result, true);
?>
Array mapping:
<?php
/* Loop through the array and only pull API fields */
$mediaUrls = array_map(function($entry) {
return [
'media_url' => $entry['media_url'],
'permalink' => $entry['permalink'],
'username' => $entry['username'],
'media_type' => $entry['media_type'],
'thumbnail_url' => $entry['thumbnail_url']
];
}, $array['data']);
?>
Via the Graph API, some have the thumbnail_url and some don't as shown below:
I am receiving an debug error as below:

Correct answer was 'thumbnail_url' => !empty($entry['thumbnail_url']) ? $entry['thumbnail_url'] : "" by #CD001.

Related

Coinmarketcap API Call with PHP

I tried my first API call but something is still wrong. I added my API-Key, choose the symbol and tried to echo the price. But it is still not valid. But my echo is still 0. Maybe someone show me what i did wrong. Thank you!
<?php
$coinfeed_coingecko_json = file_get_contents('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?symbol=ETH');
$parameters = [
'start' => '1',
'limit' => '2000',
'convert' => 'USD'
];
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: XXX'
];
$qs = http_build_query($parameters); // query string encode the parameters
$request = "{$url}?{$qs}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
print_r(json_decode($response)); // print json decoded response
curl_close($curl); // Close request
$coinfeed_json = json_decode($coinfeed_coingecko_json, false);
$coinfeedprice_current_price = $coinfeed_json->data->{'1'}->quote->USD->price;
?>
<?php echo $coinfeedde = number_format($coinfeedprice_current_price, 2, '.', ''); ?>
API Doc: https://coinmarketcap.com/api/v1/#operation/getV1CryptocurrencyListingsLatest
There is a lot going on in your code.
First of all $url was not defined
Second of all you made two requests, one of which I have removed
Third; you can access the json object by $json->data[0]->quote->USD->price
Fourth; I removed the invalid request params
I have changed a few things to make it work:
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: ___YOUR_API_KEY_HERE___'
];
$request = "{$url}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
$json = json_decode($response);
curl_close($curl); // Close request
var_dump($json->data[0]->quote->USD->price);
var_dump($json->data[1]->quote->USD->price);

Using curl to post request handle JSON data

I recently work with kraken.io API and I'm trying to integrate this API wuth my PHP CodeIgniter framework. So I followed the documentation but I got stuck when I used curl
This is my source code below ..
require_once(APPPATH.'libraries/kraken-php-master/Kraken.php');
$kraken = new Kraken("SOME_KEY", "SOME_SECRET");
$params = array(
"file" => base_url()."include/".$dataIn['logo'],
"wait" => true
);
$dataj='{"auth":{"api_key": "SOME_KEY", "api_secret": "SOME_SECRET"},"file":'.base_url()."include/".$dataIn['logo'].',wait":true}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.kraken.io/v1/upload");
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataj);
$response = curl_exec($ch);
curl_close($ch);
$data = $kraken->upload($params);
print_r($response);exit();
And I got this result
"{"success":false,"message":"Incoming request body does not contain a valid JSON object"}1"
So can anyone please help me,
And thanks in advance,
DONT POST YOUR API_KEY AND API_SECRET
The error message is quite clear, your json object is not valid. For instance this would be a valid JSON object for your request:
{
"auth": {
"api_key": "SOME",
"api_secret": "SECRET"
},
"file": "somefile.txt",
"wait": true
}
In your php code you are setting up a $params array but then you don't use it. Try this:
$dataj='{"auth":{"api_key": "SOME_KEY", "api_secret": "SOME_SECRET"},"file":"' . $params["file"]. '", "wait":true}';
You can validate your JSON HERE
You should use json_encode function to generate your JSON data
$dataj = json_encode([
"auth" => [
"api_key" => "API_KEY",
"api_secret" => "API_SECRET"
],
"file" => base_url() . "include/" . $dataIn['logo'],
"wait" => true
]);
EDIT:
Here is an example from https://kraken.io/docs/upload-url so you don't need to use curl
require_once("Kraken.php");
$kraken = new Kraken("your-api-key", "your-api-secret");
$params = array(
"file" => "/path/to/image/file.jpg",
"wait" => true
);
$data = $kraken->upload($params);
if ($data["success"]) {
echo "Success. Optimized image URL: " . $data["kraked_url"];
} else {
echo "Fail. Error message: " . $data["message"];
}

Instagram getting Access token Notice: Undefined index: access_token

I'm beginner programmer
to get Instagram Authentication, I uploaded this php code on my server
<?php
getAccessToken();
function getAccessToken(){
if($_GET['code']) {
$code = $_GET['code'];
$url = "https://api.instagram.com/oauth/access_token";
$access_token_parameters = array(
'client_id' => 'b7f14786b7754f04aa43dcxxxxxxxxxx', // my client id
'client_secret' => '33987fcae22949a9b3682bxxxxxxxxxx', // secret key
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://thedreamkr.com/',
'code' => $code
);
$curl = curl_init($url); // we init curl by passing the url
curl_setopt($curl,CURLOPT_POST,true); // to send a POST request
curl_setopt($curl,CURLOPT_POSTFIELDS,$access_token_parameters); // indicate the data to send
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // to stop cURL from verifying the peer's certificate.
$result = curl_exec($curl); // to perform the curl session
curl_close($curl); // to close the curl session
$arr = json_decode($result,true);
echo "access_Token: ".$arr['access_token']; // display the access_token
echo "<br>";
echo "user_name : ".$arr['user']['username']; // display the username
}
}
?>
and when I access to "https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code"
it returns following error
Notice: Undefined index: access_token in /home/ubuntu/php/hashberry/token.php on line 26
access_Token:
Notice: Undefined index: user in /home/ubuntu/php/hashberry/token.php on line 28
user_name :
After testing, your code works perfectly.
However:
1- You need to have your code inside of the redirect URI which is different from your website URI.
2- Change your redirect uri to match the one in your registered app.
For example :
Website URI: https://example.com/
Redirect URI: https://example.com/register/
Good luck

PHP Curl - Wistia API Upload

I'm trying to upload a movie to the Wistia API by CURL (http://wistia.com/doc/upload-api).
It works fine using the following command line, but when I put it in PHP code, I just get a blank screen with no response:
$ curl -i -d "api_password=<YOUR_API_PASSWORD>&url=<REMOTE_FILE_PATH>" https://upload.wistia.com/
PHP Code:
<?php
$data = array(
'api_password' => '<password>',
'url' => 'http://www.mysayara.com/IMG_2183.MOV'
);
$chss = curl_init('https://upload.wistia.com');
curl_setopt_array($chss, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => json_encode($data)
));
// Send the request
$KReresponse = curl_exec($chss);
// Decode the response
$KReresponseData = json_decode($KReresponse, TRUE);
echo("Response:");
print_r($KReresponseData);
?>
Thanks.
For PHP v5.5.0 or later, here's a class for uploading to Wistia, from a LOCALLY STORED file.
Usage:
$result = WistiaUploadApi::uploadVideo("/var/www/mysite.com/tmp_videos/video.mp4","video.mp4","abcdefg123","Test Video", "This is a video upload demonstration");
The class:
#param $file_path Full local path to the file
#param $file_name The name of the file (not sure what Wistia does with this)
#param $project The 10 character project identifier the video will upload to
#param $name The name the video will have on Wistia
#param $description The description the video will have on Wistia
class WistiaUploadApi
{
const API_KEY = "<API_KEY_HERE>";
const WISTIA_UPLOAD_URL = "https://upload.wistia.com";
public static function uploadVideo($file_path, $file_name, $project, $name, $description='')
{
$url = self::WISTIA_UPLOAD_URL;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
$params = array
(
'project_id' => $project,
'name' => $name,
'description' => $description,
'api_password' => self:: API_KEY,
'file' => new CurlFile($file_path, 'video/mp4', $file_name)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//JSON result
$result = curl_exec($ch);
//Object result
return json_decode($result);
}
}
If you don't have a project to upload into, leaving $project blank will NOT apparently force Wistia to create one. It will just fail. So you might have to remove this from the $params array if you don't have a project to upload to. I've not experimented to see what happens when you leave $name blank.
Your problem (and the difference between the command line and PHP implementation) is probably that you're JSON encoding the data in PHP, you should use http_build_query() instead:
CURLOPT_POSTFIELDS => http_build_query($data)
For clarity, the Wistia API says it returns JSON, but doesn't expect it in the request.

Send parameters to a URL and get output from that page

I have 2 pages say abc.php and def.php. When abc.php sends 2 values [id and name] to def.php, it shows a message "Value received". Now how can I send those 2 values to def.php without using form in abc.php and get the "Value received" message from def.php? I can't use form because when user frequently visits the abc.php file, the script should automatically work and get the message "Value received" from def.php. Please see my example code:
abc.php:
<?php
$id="123";
$name="blahblah";
//need to send the value to def.php & get value from that page
// echo $value=Print the "Value received" msg from def.php;
?>
def.php:
<?php
$id=$_GET['id'];
$name=$_GET['name'];
if(!is_null($id)&&!is_null($name))
{ echo "Value received";}
else{echo "Not ok";}
?>
Is there any kind heart who can help me solve the issue?
First make up your mind : do you want GET or POST parameters.
Your script currently expects them to be GET parameters, so you can simply call it (provided that URL wrappers are enabled anyway) using :
$f = file_get_contents('http://your.domain/def.php?id=123&name=blahblah');
To use the curl examples posted here in other answers you'll have to alter your script to use $_POST instead of $_GET.
You can try without cURL (I havent tried though):
Copy pasted from : POSTing data without cURL extension
// Your POST data
$data = http_build_query(array(
'param1' => 'data1',
'param2' => 'data2'
));
// Create HTTP stream context
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $data
)
));
// Make POST request
$response = file_get_contents('http://example.com', false, $context);
Taken from the examples page of php.net:
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "example.com/abc.php");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
Edit: To send parameters
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( tch, CURLOPT_POSTFIELDS, array('var1=foo', 'var2=bar'));
use CURL or Zend_Http_Client.
<?php
$method = 'GET'; //change to 'POST' for post method
$url = 'http://localhost/browse/';
$data = array(
'manufacturer' => 'kraft',
'packaging_type' => 'bag'
);
if ($method == 'POST'){
//Make POST request
$data = http_build_query($data);
$context = stream_context_create(array(
'http' => array(
'method' => "$method",
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $data)
)
);
$response = file_get_contents($url, false, $context);
}
else {
// Make GET request
$data = http_build_query($data, '', '&');
$response = file_get_contents($url."?".$data, false);
}
echo $response;
?>
get inspired by trix's answer, I decided to extend that code to cater for both GET and POST method.

Categories