Unable to get json data from rest api in php - php

code:
<?php
$url = base_url()."eventapi";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
var_dump(json_decode($result, true));
?>
eventapi controller
<?php
require APPPATH . '/libraries/REST_Controller.php';
use Restserver\Libraries\REST_Controller;
class Eventapi extends REST_Controller
{
function __construct()
{
parent::__construct();
$this->load->database();
}
function index_get()
{
$data['client_id'] = $this->session->userdata('client_id');
$client_id = $data['client_id'][0]['client_id'];
$this->db->select('*');
$this->db->from('event');
$this->db->where('client_id',$client_id);
$sql = $this->db->get();
$result = $sql->result_array();
$this->response($result, 200);
}
}
output:
array(0) { }
eventapi data
[{"id":"1","client_id":"20190702082406","event_type":"Private Event","event_name":"Birthday Celebration","event_date":"2019-08-15","event_time":"08:00 PM","event_des":"Birthday celebration ","s_date":"2019"}]
I am creating a simple rest API using Codeigniter where API works fine. Now, the problem is that when I am getting data from eventapi using curl it shows me output i.e array(0) { } I don't know why? So, How can I solve this issue? Please help me.
Thank You

If the above one is your code, you didn't add any parameters. The array passing with empty input. So you get empty output. Please correct the input.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
$inputParameters");
Please add these lines along with the curl .
And don't forget to add the header also .
//set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
//return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Related

Pulling in optional parameters for Emma API using php

I am trying to get additional parameters from Emma's API using php. If anyone can point me in the right direction, I would greatly appreciate it. I know that my problem is terminology and thnk I am struggling with the basics and just need to "get over the hump."
I have been able to successfully test getting the basic fields that Emma provides by using get curl https://api.e2ma.net/account_id/mailings and --header 'Authorization: Basic {{public_api_key}}:{{private_api_key}}'
My problem is that according to their documentation (url below), I should be able to include extra parameters (I need to get the with_html_body parameter).
http://api.myemma.com/api/external/mailings.html
The code below gives me the following error:
Error getting member: {"error": "Unable to parse JSON request"}
I know the $data array is the problem.
Any idea if this is my only problem?
I figure I need to pull in the with_html_body field as an array and then CURLOPT_POSTFIELDS the variable ($data).
Amy I way off base?
Thanks in advance for any help pointing me in the right direction.
<?php
// Authentication Variables
$account_id = "1111111";
$public_api_key = "99999999";
$private_api_key = "99898989";
// Set URL
$url = "https://api.e2ma.net/" . $account_id . "/mailings";
// Open connection
$ch = curl_init();
$data = array('with_html_body' => 'true');
// Make the curl call
curl_setopt($ch, CURLOPT_USERPWD, $public_api_key . ":" . $private_api_key);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$head = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//curl_close($ch);
// check for errors
if($http_code > 200) {
print "Error getting member:\r\n";
print_r($head);
} else {
/*
print "Member information:\r\n";
print_r($head);
*/
$decoded = json_decode($head, true);
echo "<pre>";
print_r($head);
echo "</pre>";
/*
*/
}
curl_close($ch);
?>
Typical me, I over-complicated the issue!
All I needed to do was adjust the $url to below.
$url = "https://api.e2ma.net/" . $account_id . "/mailings?with_html_body=true";
Yes, I feel like an idiot!
But making progress.
Now to put this code in a better form to use on a project.

How can I access the property of an object in PHP from the result of a separate PHP file?

I'll try to keep this short and to the point. I'm setting up an API which requires using POST to generate an 'authorization token', which I can then use in combination with GET to retrieve data. The results are in JSON format, of course. I have an auth.php file which works and gives the token, among other object properties. My question is how do I use the token in a separate GET.php file to retrieve the data I need?
Is there a way to access Object properties from the end result of my auth.php file?
Here is the code which isn't working in my GET.php file:
if (isset($_POST['TOKEN'])) {
$api_key = '11111111111111111111111111111';
$utoken = $_POST['TOKEN'];
$url = 'https://api.rmaster.com/api/daltonwholesale/catalogattributes?company='.$company.'&catseq='.$catseq.'&api_key='.$api_key;
$company = '99';
$catseq = '98838';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$result = curl_exec($ch);
if (!$result) {die("Connection Failure");}
curl_close($ch);
echo $result;
} else {
echo $_POST['TOKEN'];
}
?>```

Github api request with php curl

I am trying to get the latest commit from github using the api, but I encounter some errors and not sure what the problem is with the curl requests. The CURLINFO_HTTP_CODE gives me 000.
What does it mean if I got 000 and why is it not getting the contents of the url?
function get_json($url){
$base = "https://api.github.com";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $base . $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($curl, CONNECTTIMEOUT, 1);
$content = curl_exec($curl);
echo $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return $content;
}
echo get_json("users/$user/repos");
function get_latest_repo($user) {
// Get the json from github for the repos
$json = json_decode(get_json("users/$user/repos"),true);
print_r($json);
// Sort the array returend by pushed_at time
function compare_pushed_at($b, $a){
return strnatcmp($a['pushed_at'], $b['pushed_at']);
}
usort($json, 'compare_pushed_at');
//Now just get the latest repo
$json = $json[0];
return $json;
}
function get_commits($repo, $user){
// Get the name of the repo that we'll use in the request url
$repoName = $repo["name"];
return json_decode(get_json("repos/$user/$repoName/commits"),true);
}
I use your code and it will work if you add an user agent on curl
curl_setopt($ch, CURLOPT_USERAGENT,'YOUR_INVENTED_APP_NAME');

How can I have a public function to run all my PHP cURL requests?

I have a basic RESTful API setup using cURL for all my requests.
At the moment, I am attempting to split out all my functions to have one function that runs all my requests.
For example, I have the following which can be called from localhost/api/getUserData
private function getUserData() {
$url = 'localhost/api/users/';
runApiCall($url);
}
That function then goes on to pass the URL to runApiCall(), which is the following:
function runApiCall($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' . $_COOKIE['PHPSESSID']);
$result = curl_exec($ch);
curl_close($ch);
$this->response($result, 200);
}
Although, I keep getting an error in my console of http://localhost/api/getUserData 500 (Internal Server Error)
The API was working perfectly fine before I split it out.
EDIT:
If I simply change my getUserData() function to the following, it works perfectly fine:
private function getUserData() {
$url = 'localhost/api/users/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' . $_COOKIE['PHPSESSID']);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$this->response($this->json($result), $status);
}
You have an issue with scope as you are inside a class.
private function getUserData() {
$url = 'localhost/api/users/';
$this->runApiCall($url); // call $this object's runAppCall() function
}
If you had error handling enabled, you'd see an error thrown by PHP telling you that it could not find the method runApiCall(). This is because you are inside a class and must explicitly tell PHP to run the method on the class.
You can do this by:
private function getUserData() {
$url = 'localhost/api/users/';
// EITHER
$this->runApiCall($url);
// OR
self::runApiCall($url);
}
In future, I'd recommend adding this line at the route of your application when you are developing, then set it to false in production:
ini_set('display_errors', 1);
This will now log any PHP errors to the browser, making it much easier for you to debug.

Facebook JSON Decoding Events in PHP

I have:
$user = json_decode(file_get_contents(
'https://graph.facebook.com/me?access_token=' .
$cookie['access_token']), true);
var_dump($user);
which works fine and gives profile output.
But:
$events = json_decode(file_get_contents(
'https://graph.facebook.com/me/events?access_token=' .
$cookie['access_token']), true);
var_dump($events);
gives:
object(stdClass)#5 (1) { ["data"]=> array(0) { } }
I'm not sure if this is an empty object, or if I'm not accessing what's inside 'data' correctly. But, I know there are in fact events associated with my profile. Permissions have been granted, so that's not the problem. Anyone know how to return all event names for my profile?
In order to get events in PHP you have to follow these steps,
Request a proper Access Token follow this link
facebook: permanent Page Access Token?
Replace your Access token below texted YOUR_ACCESS_TOKEN field
<?php
$json_string = 'https://graph.facebook.com/5973249561/events/?access_token=YOUR_ACCESS_TOKEN&fields=id,name,description,start_time,place,cover,end_time&limit=999';
$obj = json_decode(curl_get_contents($json_string),true);
foreach ($obj['data'] as $key => $value) {
echo #$value['id'];
echo #$value['name'];
echo #$value['start_time'];
echo #$value['place'];
echo #$value['cover']['source'];
}
function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
?>

Categories