I have create a REST API and want to consume my own created API in codeigniter controller.
My created REST API
controller(example.php)
class Example extends REST_Controller {
public function __construct() {
parent::__construct();
$this->load->model('user');
}
public function user_fetch_post() {
//returns all rows if the id parameter doesn't exist,
//otherwise single row will be returned
$id = $this->input->post('id');
$users = $this->user->getRows($id);
//check if the user data exists
if(!empty($users)){
//set the response and exit
$this->response($users, REST_Controller::HTTP_OK);
}else{
//set the response and exit
$this->response([
'status' => FALSE,
'message' => 'No user were found.'
], REST_Controller::HTTP_NOT_FOUND);
}
}
model(user.php)
function getRows($id = ""){
if(!empty($id)){
$query = $this->db->get_where('users', array('id' => $id));
return $query->row_array();
}else{
$query = $this->db->get('users');
return $query->result_array();
}
}
Here i want to call my created api(from example.php)for fetch record in welcome.php controller with basic authentication(uname-admin,pwd-1234)
my controller welcome.php
public function index()
{
}
Can anybody help to me that how to call my api in controller welcome.php with basic authentication.
Using CURL you can consume any API/network call.
<?php
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode("user:password") // place your auth details here
);
$payload = array(
'id' => 1,
);
$process = curl_init($host); //your API url
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $payload);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
curl_close($process);
//finally print your API response
print_r($return);
?>
But why are you calling your own API this way? You can simply call your API model and perform your operations
Add below to your curl options
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'APIKEY: admin#123',
'Content-Type: application/json',
));
also update
$config['rest_key_name'] = 'APIKEY';
in rest.php file inside config folder of your codeigniter settings. By default it is 'X-API-KEY'
This may help to somebody else looking for a solution, if OP has resolved it himself/herself.
Related
I have a Yii2 application. I would like to connect it to another restful webpage. So user will send data to my application, I will send them via POST request and do something according to a JSON response. How can I do the send a request / fetch response part in a yii2?
The best method would be to use curl to make end to end calls to your RESTful API, in which case you may be interested in checking out a yii2 extension for curl.
Without a Yii2 extension, we can accomplish this by creating a more general function in a controller or more preferably a model (for shared access) as exampled below:
/**
* $method e.g POST, GET, PUT
* $data = [
'param' => 'value',
]
*/
public function curlToRestApi($method, $url, $data = null)
{
$curl = curl_init();
// switch $method
switch ($method) {
case 'POST':
curl_setopt($curl, CURLOPT_POST, 1);
if($data !== null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
break;
// logic for other methods of interest
// .
// .
// .
default:
if ($data !== null){
$url = sprintf("%s?%s", $url, http_build_query($data));
}
}
// Authentication [Optional]
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
We then call this function on a need basis i.e. depending on the method and url and/or data.
It is also conveniently easy to use file_get_contents if fopen wrapper is enabled in order to access Web Service URLs.
$response = file_get_contents('http://example.com/path/to/api?param1=stack¶m2=overflow');
If a JSON response is served, you can recover the php array as follows:
$response = json_decode($response, TRUE);
If an XML response is returned, then
$response = new \SimpleXMLElement($response);
However, if the API endpoint returns an HTTP error status, the file_get_contents function fails with a warning and returns null.
Can someone take a look at how I've set up this REST call? I haven't been able to find an example of this, and I can't get it to work.
It may be the blank 'link_name_to_fields_array' parameter. I have read the documentation and don't really understand that parameter. I don't know if that is causing my problem or not.
Any help would be apprecitated.
//SET UP CURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//parameters for get_entry call (I received a session id from a call to the login function. Using it here)
//I manually got this user 'id' form the sugarcrm database
$parameters = array(
'session'=>$result->id,
'module_name' => 'users',
'id' => '21a6a633-40de-9bf4-aa14-4f8753ea5aa2',
'select_fields' => array('user_name'),
'link_name_to_fields_array'=> array()
);
$json = json_encode($parameters);
$postArgs='method=get_entry&input_type=JSON&response_type=JSON$rest_data=' . $json;
curl_setopt($curl,CURLOPT_POSTFIELDS, $postArgs);
$result2 = curl_exec( $curl );
echo("<pre>" . print_r($result2,true) . "</pre>");
The output is "Bad data passed in; Return to Home"
You have an error in the postArgs line (replace $rest_data with &rest_data). Try with this:
$postArgs='method=get_entry&input_type=JSON&response_type=JSON&rest_data=' . $json;
I finally have a working script to submit Facebook Events remotely, and have finished tackling the problem of converting my site's events RSS feed to the FB Events data. Utilizing RSS2HTML, I have added in a template-based call to send each event over two days before the event. Here's the code:
// Post Today's Game
if (strstr($template, "~~~TwitterToday~~~"))
{
//Build Arrays for games (when there are more than one per day...
$name = array( 'name' );
$desc = array( 'description' );
$venue = array( 'location' );
$s_time = array( 'start_time' );
$e_time = array( 'end_time' );
$pic = array( 'picture' );
$priv = array( 'privacy' );
//Build Main Facebook Array for All games to draw from
$fbook = array(
$name,
$desc,
$venue,
$s_time,
$e_time,
$pic,
$priv,
);
$template = str_replace("~~~TwitterToday~~~", "", $template);
$mycount = 1;
for ($y = 1; $y < count($rss_parser->Items)+1; $y++) //come back through events
{
//find each event's information to look for today's
$gamedate = date('n/j/Y', $rss_parser->Items[$y]->pubDate_t);
$todaysdate = date('n/j/Y');
$tomorrowsdate = date('n/j/Y',mktime(0,0,0,date('m'), date('d')+1, date('Y')));
$gametime = date('Y-m-d H:i:s',$rss_parser->Items[$y]->pubDate_t);
$title = $rss_parser->Items[$y]->title;
$description = $rss_parser->Items[$y]->description;
if ($gamedate == $tomorrowsdate) //found it
{
$mycount++;
//Fill the arrays
$name[] = $title;
$desc[] = $description;
$venue[] = "Home";
$s_time[] = $gametime;
$e_time[] = "";
$pic[] = "";
$priv[] = "OPEN";
}
} // end $y loop
//Populate Main Facebook Array
$fbook[0] = $name;
$fbook[1] = $desc;
$fbook[2] = $venue;
$fbook[3] = $s_time;
$fbook[4] = $e_time;
$fbook[5] = $pic;
$fbook[6] = $priv;
// Let's run with it
if (strpos($title,"Special Event") === false)
{
$page_id = "xxxxxxxxxxxxxx"; //First Page Id
}
else
{
$page_id = "xxxxxxxxxxxxxxxxxxx"; //Special Event Page Id
}
$app_id = "xxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
$my_url = "http://mydomain.com/feeds/rss2html.php"; // URL to THIS script
//Going to get the PAGE access code
//First to get USER Access Code
session_start();
$code = $_REQUEST["code"];
if (empty($code))
{
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state=" . $_SESSION['state'] . "&scope=create_event&scope=manage_pages";
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if ($_REQUEST['state'] == $_SESSION['state'])
{
$token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret=" . $app_secret . "&code=" . $code;
$access_token = #file_get_contents($token_url);
$params = null;
parse_str($access_token, $params);
$graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
}
else
{
echo("The state does not match. You may be a victim of CSRF.");
}
//Now, getting the PAGE Access token, using the user access token
$page_token_url = "https://graph.facebook.com/" . $page_id . "?fields=access_token&" . $access_token;
$response = file_get_contents($page_token_url);
// Parse the return value and get the Page access token
$resp_obj = json_decode($response,true);
$page_access_token = $resp_obj['access_token'];
for ($s = 1; $s < $mycount+1; $s++)
{
//Let's go post it up!
$url = "https://graph.facebook.com/" . $page_id . "/events?access_token=" . $page_access_token;
$params = array();
// Prepare Event fields
$params = array(
'name' => $fbook[0][$s],
'description' => $fbook[1][$s],
'location' => $fbook[2][$s],
'start_time' => $fbook[3][$s],
// 'end_time' => $fbook[4][$s], //These need to be excluded if they are empty
// 'picture' => $fbook[5][$s],
'privacy' => $fbook[6][$s],
);
// Start the Graph API call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
$decoded = json_decode($result, true);
curl_close($ch);
if (is_array($decoded) && isset($decoded['id']))
{
$msg = "Event created successfully: {$decoded['id']}";
}
echo '<hr />' . $msg;
}
/* End FaceBook Code */
}
This script works wonders when I call it from my browser, but when calling it from the cron job, I get an "Unable to open template" error in the rss2html script. In the past, I have always been able to solve this by making a separate script for the cron job, essentially using cURL to call the feed, and it works wonders.
Unfortunately, this technique won't work with a FaceBook Auth script, because it then returns the "The state does not match. You may be a victim of CSRF."
So, I'm between a rock and a hard place. Can't run the rss2html script without the cURL call, and the cURL call impedes the Facebook login. Here's a text version of the rss2html script as it stands, in case anyone wants to see it.
Can anyone think of a good workaround one way or t'other?
Thanks to DCMS, solution went thusly:
Using Facebook's Authentication Docs at https://developers.facebook.com/docs/authentication/ and adding '&scope=offline_access" to my call, I was able to grab some offline access tokens, and altered my above code thusly:
//Going to get the PAGE access code
//First to get USER Access Code
session_start();
for ($s = 1; $s < $mycount+1; $s++)
{
//Let's go post it up!
$url = "https://graph.facebook.com/" . $page_id . "/events?access_token=" . $page_access_token;
$params = array();
// Prepare Event fields
$params = array(
'name' => $fbook[0][$s],
'description' => $fbook[1][$s],
'location' => $fbook[2][$s],
'start_time' => $fbook[3][$s],
// 'end_time' => $fbook[4][$s], //These need to be excluded if they are empty
// 'picture' => $fbook[5][$s],
'privacy' => $fbook[6][$s],
);
// Start the Graph API call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
$decoded = json_decode($result, true);
curl_close($ch);
if (is_array($decoded) && isset($decoded['id']))
{
$msg = "Event created successfully: {$decoded['id']}";
}
echo '<hr />' . $msg;
}
/* End FaceBook Code */
}
Thanks for the help, and I hope this helps anyone to come along with the same issue in the future!
Your solution might be to store the access token. Request offline_access and grab that token and hold onto it. Then use that token for your Graph API calls.
I would like to submit my form to another page but making it not go to that page (like AJAX, but I know that AJAX does not work across domains)
Do you guys know how to do this? I don't like submitting it to the page on the other site because it is just really a slower and crappier way of doing things.
Thanks,
Nathan Johnson
Submit your form to a local page via AJAX. From that page you can post the data to the remote site with e.g. cURL.
Here's a very abstract example:
page_with_form.php
<form id="form1">
//input fields
</form>
<script>
$.post('post_to_remote.php', $('#form1').serialize(), function(){
//do something when finished
return false; //prevent from reloading
});
</script>
post_to_remote.php
$param1 = $_POST['param1'];
$param2 = $_POST['param2'];
$remoteUrl = 'http://www.remote_site.com/page_to_post_to.php';
$postFields = array('param1' => $param1, 'param2' => $param2);
//if you don't want to do any sanitizing, you can also simply do this:
//$postFields = $_POST;
$data_from_remote_page = $getUrl($remoteUrl, 'post', $postFileds);
function getUrl($url, $method='', $vars='') {
$ch = curl_init();
if ($method == 'post') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
$buffer = curl_exec($ch);
curl_close($ch);
return $buffer;
}
If you do not need the full power of curl and it's really just a simple post, you can also use native PHP functions:
$postFields = http_build_query($_POST);
$remoteUrl = 'http://www.remote_site.com/page_to_post_to.php';
$context = stream_context_create(
array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'content' => $postFields,
'timeout' => 10,
),
)
);
$result = file_get_contents($remoteURL, false, $context);
A vary basic example, but you get the idea.
You can try using JSONP:
http://davidwalsh.name/jsonp
http://api.jquery.com/jQuery.getJSON/#jsonp
It can be used cross-domain, but the data you send back from the server has to be something like (PHP):
echo $_GET['callback']."(".json_encode($data).")";
When I first used it I didn't echoed the callback function's name and it took me a couple of hours to see why it wasn't working.
Good luck!
Try jsonp in javascript:
$.ajax({
url: 'some_url' ,
data: $('#form_id').serialize(),
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallbask"
});
function jsonpcallbask(data) {
//handle response here
}
I wanted to ask if/how is it possible to tag a photo using the FB API (Graph or REST).
I've managed to create an album and also to upload a photo in it, but I stuck on tagging.
I've got the permissions and the correct session key.
My code until now:
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$token = $session['access_token'];//here I get the token from the $session array
$album_id = $album[0];
//upload photo
$file= 'images/hand.jpg';
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath($file);
$ch = curl_init();
$url = 'https://graph.facebook.com/'.$album_id.'/photos?access_token='.$token;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
//returns the id of the photo you just uploaded
print_r(json_decode($data,true));
$search = array('{"id":', "}");
$delete = array("", "");
// picture id call with $picture
$picture = str_replace($search, $delete, $data);
//here should be the photos.addTag, but i don't know how to solve this
//above code works, below i don't know what is the error / what's missing
$json = 'https://api.facebook.com/method/photos.addTag?pid='.urlencode($picture).'&tag_text=Test&x=50&y=50&access_token='.urlencode($token);
$ch = curl_init();
$url = $json;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_exec($ch);
} catch(FacebookApiException $e){
echo "Error:" . print_r($e, true);
}
I really searched a long time, if you know something that might help me, please post it here :)
Thanks for all your help,
Camillo
Hey,
you can tag the Picture directly on the Upload with the GRAPH API,
see the example below:
This Method creates an array for the tag information, in this examples the method becomes an array with Facebook user Ids:
private function makeTagArray($userId) {
foreach($userId as $id) {
$tags[] = array('tag_uid'=>$id, 'x'=>$x,'y'=>$y);
$x+=10;
$y+=10;
}
$tags = json_encode($tags);
return $tags;
}
Here are the arguments for the call of the GRAPH API to upload an picture:
$arguments = array(
'message' => 'The Comment on this Picture',
'tags'=>$this->makeTagArray($this->getRandomFriends($userId)),
'source' => '#' .realpath( BASEPATH . '/tmp/'.$imageName),
);
And here is the Method for the GRAPH API call:
public function uploadPhoto($albId,$arguments) {
//https://graph.facebook.com/me/photos
try {
$fbUpload = $this->facebook->api('/'.$albId.'/photos?access_token='.$this->facebook->getAccessToken(),'post', $arguments);
return $fbUpload;
}catch(FacebookApiException $e) {
$e;
// var_dump($e);
return false;
}
}
The argument $albId contains an ID from an Facebook Album.
And if you want to Tag an existing Picture from an Album you can user this Method:
At First we need the correct picture ID from the REST API, In this example we need the Name from an Album wich the Application has create or the user wich uses this Application.
The Method returns The Picture ID From the last Uploaded Picture of this Album:
public function getRestPhotoId($userId,$albumName) {
try {
$arguments = array('method'=>'photos.getAlbums',
'uid'=>$userId
);
$fbLikes = $this->facebook->api($arguments);
foreach($fbLikes as $album) {
if($album['name'] == $albumName) {
$myAlbId = $album['aid'];
}
}
if(!isset($myAlbId))
return FALSE;
$arguments = array('method'=>'photos.get',
'aid'=>$myAlbId
);
$fbLikes = $this->facebook->api($arguments);
$anz = count($fbLikes);
var_dump($anz,$fbLikes[$anz-1]['pid']);
if(isset($fbLikes[$anz-1]['pid']))
return $fbLikes[$anz-1]['pid'];
else
return FALSE;
//var_dump($fbLikes[$anz-1]['pid']);
//return $fbLikes;
}catch(FacebookApiException $e) {
$e;
// var_dump($e);
return false;
}
}
Now you have the correct picture ID From the REST API and you can make your REST API CALL to tag this Picture $pid is the Picture from the Method getRestPhotoId and $tag_uid is an Facebook userId:
$json = 'https://api.facebook.com/method/photos.addTag?pid='.$pid.'&tag_uid='.$userId.'&x=50&y=50&access_token='.$this->facebook->getAccessToken();
$ch = curl_init();
$url = $json;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_GET, true);
$data = curl_exec($ch);
And this line is very important:
curl_setopt($ch, CURLOPT_GET, true);
you must youse CUROPT_GET instead of CUROPT_POST to add a Tag throw the REST API.
I Hope this helps you.
Best wishes Kay from Stuttart
Photo id is unique for every user and looks like two numbers joined by underscore in the middle.
Getting this id is a bit tricky.
You can get it by running FQL on photo table but you need to provide album id which is also user unique. You can get album id from album table but you need to provide owner userid.
For example we have CocaCola user with userid 40796308305. To get photo ids from this user we can run FQL:
SELECT pid FROM photo WHERE aid IN ( SELECT aid FROM album WHERE owner="40796308305")
(you can run it in a test console on this page)
This would return our photo ids:
[
{
"pid": "40796308305_2298049"
},
{
"pid": "40796308305_1504673"
},
{
"pid": "40796308305_2011591"
},
...
]
I didn't work with photos much, maybe you don't have to go through all this process to get photo id, it might be some simple algorithm like <OWNER_ID>_<PHOTO_ID>. But try to get your photo id from FQL and see if tagging would work. If it does maybe you will be able to skip FQL part and build photo id from existing data you have.
Hopefully this helps.
I found out the problem, the problem is that when you use curl to send the array the post function will not send the array correctly, it was sending just "Array" that it was why the graph API complained about tags being an array. To solve that I did the following:
$data = array(array('tag_uid' => $taguser,
'x' => rand() % 100,
'y' => rand() % 100
));
$data = json_encode($data);
$photo_details = array(
'message'=> $fnames,
'tags' => $data
);
Now I just send using curl
curl_setopt($ch, CURLOPT_POSTFIELDS, $photo_details);