getLogoutUrl is not working with facebook graphp api using php codeigniter - php

My facebook php sdk getLogoutUrl is not working when i click on my logout url.
it takes me back to my given redirect url but it does not destroy my facebook session i can still see my var_dump($fb_data) array on my page and logout url.
Here is my code i am using codeigniter
My lib_login library function facebook code
public function facebook()
{
$facebook_default_scope = explode(',', $this->ci->config->item("facebook_default_scope"));
$facebook_app_id = $this->ci->config->item("facebook_app_id");
$facebook_api_secret = $this->ci->config->item("facebook_api_secret");
// init app with app id and secret
FacebookSession::setDefaultApplication($facebook_app_id, $facebook_api_secret);
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper(site_url('login/facebook'));
// see if a existing session exists
if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
// create new session from saved access_token
$session = new FacebookSession($_SESSION['fb_token']);
// validate the access_token to make sure it's still valid
try {
if (!$session->validate()) {
$session = null;
}
} catch (Exception $e) {
// catch any exceptions
$session = null;
}
}
if (!isset($session) || $session === null) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
// handle this better in production code
print_r($ex);
} catch(Exception $ex) {
// When validation fails or other local issues
// handle this better in production code
print_r($ex);
}
}
// see if we have a session
if (isset($session)) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession($session->getToken());
// graph api request for user data
$request = new FacebookRequest($session, 'GET', '/me?fields=id,name,accounts{access_token,category,name,id,perms},permissions');
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
$logoutUrl = site_url('login');
$fb_data = array(
'me' => $graphObject,
'loginUrl' => $helper->getLoginUrl($facebook_default_scope),
'logoutUrl' => $helper->getLogoutUrl($session,$logoutUrl),
);
$this->ci->session->set_userdata('fb_data', $fb_data);
} else {
$fb_data = array(
'me' => null,
'loginUrl' => $helper->getLoginUrl($facebook_default_scope),
'logoutUrl' => $helper->getLogoutUrl($session,$logoutUrl),
);
$this->ci->session->set_userdata('fb_data', $fb_data);
}
return $fb_data;
}
Here is my function of my controller
public function facebook()
{
$fb_data = $this->lib_login->facebook();
if (isset($fb_data['me'])) {
echo "<pre>";
var_dump($fb_data);
echo "</pre>";
echo 'logout';
} else {
echo 'Login';
}
}
When ever i login to my account using this code then the logout url and $fb_data array appears on my page but when i logout and refresh my page it is still their.Can some one tell what i am doing wrong here.

Try something like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library(array('session', 'lib_login'));
$this->fb_data = $this->lib_login->facebook();
}
/**
* facebook login
*
* #return void
* #author appleboy
**/
public function facebook()
{
// check login data
if (isset($this->fb_data['me'])) {
var_dump($this->fb_data);
} else {
echo 'Login';
}
}
public function logout()
{
if ( isset($this->fb_data['me']) ) {
$this->session->unset_userdata('fb_data');
}
redirect('login/facebook', 'refresh');
}
}
/* End of file login.php */
/* Location: ./application/controllers/login.php */

Related

facebook login with codeigniter error URL blocked

I have a code from a tutorial to login with facebook. Now when i go to the login with facebook, it says error with
URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.
I already configure my appsettings with the settings in this screenshot:
setup from Oauth:
i am using codeigniter with these codes :
<?php
include(APPPATH.'libraries/facebook/src/facebook.php');
class Connect extends Facebook {
public $user = null;
public $user_id = null;
public $fb = false;
public $fbSession = false;
public $appkey = 0;
public function Connect() {
$ci =& get_instance();
$ci->config->load('facebook',TRUE);
$config = $ci->config->item('facebook');
// echo $config['appId'];
parent::__construct($config);
$this->user_id = $this->getUser();
$me = null;
if($this->user_id){
try {
$me = $this->api('/me');
$this->user = $me;
} catch (FacebookApiException $e) {
error_log($e);
}
}
}
}
and with this in my controller:
public function facebook_request(){
$data = array (
'redirect_uri' => base_url('authentication/handle_facebook_login'),
'scope' => 'email'
);
var_dump($data);
$this->load->library('connect');
redirect($this->connect->getLoginUrl($data));
}
public function handle_facebook_login() {
$this->load->library('connect');
if($this->connect->user) {
print_r($this->connect->user);
} else {
}
}

Soundcloud php API The requested URL responded with HTTP code 0

I am getting the response below when trying to upload a file to soundcloud using the soundcloud php api.
The requested URL responded with HTTP code 0.
When trying to upload a file through the api.
It will get my data fine but not upload here is my full codeignitor controller.
I have tried all the suggested option to add the CURLOPT_SSL_VERIFYPEER, false but this doesnt seem to work for me can someone confirm it is working so i can narrow it down to my server.
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/*
* Soundcloud Controller
*/
class Soundcloud extends CI_Controller {
/**
* Constructor
*/
function __construct()
{
parent::__construct();
require APPPATH.'/libraries/php-soundcloud-master/Services/Soundcloud.php';
$this->soundcloud = new Services_Soundcloud('api key', 'api key', 'redirect uri');
}
function index(){
$authorizeUrl = $this->soundcloud->getAuthorizeUrl();
// Redirect to authorize url
echo 'Connect with SoundCloud';
}
function getme(){
$url = $_SERVER['DOCUMENT_ROOT'] . '/' . APPPATH . 'libraries/php-soundcloud-master/test/test.mp3';
try {
$accessToken = $this->soundcloud->accessToken($_GET['code']);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
/*
$this->soundcloud->setCurlOptions(array(
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0
));
*/
try {
$me = json_decode($this->soundcloud->get('me'), true);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
// this will print out all my data fine
echo "<pre>";
print_r($me);
echo "</pre>";
$track_data = array(
//'track[sharing]' => 'private',
'track[title]' => 'Testing API',
//'track[tags]' => null,
'track[asset_data]' => '#' . $url
);
// perform the actual upload to soundcloud.
try {
$response = json_decode(
$this->soundcloud->post('tracks', $track_data),
true
);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
show_error($e->getMessage());
}
}
}

Check if already logged to facebook with PHP SDK 4.0

I want to check if already logged in to facebook when navigating to index.php so I would automatically redirect to homepage.
However, my code will only check after clicking on the loggin link.
Facebook\FacebookSession::setDefaultApplication(Globals::FB_APP_ID, Globals::FB_APP_SECRET);
$helper = new Facebook\FacebookRedirectLoginHelper("myurl");
try {
$session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
} catch (Exception $ex) {
// When validation fails or other local issues
}
// see if we have a session
if (isset($session)) {
// graph api request for user data
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
header("location:home.php");
} else {
// show login url
echo 'Login';
}
I checked some other thread about Facebook PHP SDK but there is not much about sdk 4.0. And nothing that worked for me..
I tought I could add a token in the session, however it wouldn't work if I would already be logged in to facebook before my first visit... It would also cause problem if I would logout from facebook without logout from my website.
Since I found this question to be frequently asked without answer, I decided to share what I did with the community.
The $session variable in my code contains an access token which can be used for re-instanciating the session anywhere else simply doing a new FacebookSession('token').
Considering that, when logging in for the first time, I retrieve the token from the $sessionand store it in $_SESSION. Then, I created a simple util function which first check if the $_SESSIONvariable is set, then try to instanciate a new FacebookSession using the stored token. If the stoken is invalid, the session won't instanciate then I can detect it in my util function and return wether the user is actually logged in or not.
Note that an access token is invalidated when facebook user logout.
Login url + token storage :
FacebookSession::setDefaultApplication(Globals::FB_APP_ID, Globals::FB_APP_SECRET);
$helper = new Facebook\FacebookRedirectLoginHelper("http://localhost/PoubellesDeMerde/PoubellesDeMerde/index.php");
try {
$session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
} catch (Exception $ex) {
// When validation fails or other local issues
}
// see if we have a session
if (isset($session)) {
// graph api request for user data
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$_SESSION['token'] = $session->getToken();
} else {
// show login url
echo 'Login';
}
Util function :
public static function isLoggedIn()
{
$id=0;
if(isset($_SESSION['token']))
{
$session = new FacebookSession($_SESSION['token']);
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject();
$id = $graphObject->getProperty("id");
}
return $id!=0;
}

Facebook PHP API: getUser returns 0

Using Codeigniter framework with Facebook's PHP SDK and Javascript SDK.
Here is my code.
public function __construct(){
parent::__construct();
$this->load->library('session');
$this->config->load('facebook');
$this->load->library('Facebook',array('appId'=>$this->config->item('appID'),'secret'=>$this->config->item('appSecret')));
}
function fblogin(){
$base_url=$this->config->item('base_url');
$user = $this->facebook->getUser();
log_message('info','>>>>>>>>>>>>User id is::'.$this->config->item('appID').'::'.$this->config->item('appSecret').' For session '.session_id());
if($user == 0){
$loginUrl = $this->facebook->getLoginUrl(array("scope"=>"user_about_me"));
redirect("$loginUrl","location");
}
if($user){
try{
$user_profile = $facebook->api('/me');
$params = array('next' => $base_url.'fbci/logout');
$ses_user=array('User'=>$user_profile,
'logout' =>$facebook->getLogoutUrl($params)
);
$this->session->set_userdata($ses_user);
redirect('/','refresh');
header('Location: '.$base_url);
}catch(FacebookApiException $e){
log_message('error',error_log($e));
$user = NULL;
}
}
Javascript
FB.login(function(response) {
console.log('fb respone'+response.serialize());
if(response.authResponse) {
parent.location ="<?php echo site_url('fbci/fblogin');?>";
}
},{scope: 'email,read_stream,publish_stream,user_birthday,user_location,user_work_history,user_hometown,user_photos'});
});
Added Facebook.php and base_facebook.php in libraries folder. This code looks straight forward but not getting what is wrong with it.

I found No way to build facebook integration with my website

I tried in many ways.. i used php-sdk and in many other ways... but i am not able to connect my website with facebook... actually.. i am doing my project in codeigniter. Can anybody plz suggest me to connect to facebook login and share using codeigniter.
<?php
include "libs/facebook.php";
$facebook = new Facebook(array(
'appId' => '376406812408828',
'sec`enter code here`ret' => 'ca1eb65bde82a4009c31b4a5adb047b5',
'cookie' => true
));
print_r($facebook);
$session = $facebook->getUser();
echo $session;
$me=null;
if($session)
{
try
{
$me = $facebook->api('/me');
echo $me;
$facebook->api('/me/feed','post',array('message' => 'Hello World!'));
}
catch(FacebookApiException $e)
{
echo $e->getMessage();
}
}
if($me)
{
$logoutUrl = $facebook ->getLogoutUrl();
echo "Logout";
}
else
{
$loginUrl = $facebook ->getLoginUrl(array(
'req_perms' => 'publish_stream,read_friendlists'
));
echo "Login";
}
?>
Danny Tran has provided A Simple & Easy Facebook Library for CodeIgniter.
CI_Facebook is a Facebook Library for CodeIgniter.
Simply copy/merge all the files into the corresponding locations and
setup config/facebook.php.
There are unit tests written for each function/class. You will need
PHPUnit to execute them.
Accessing the Facebook object is easy since the hook is auto-loading
it.
e.g. $user_data = $this->facebook->fb->api_client->fql_query("select name from user where uid = TARGETUSERID");
Link to library on Github: https://github.com/dannybtran/CI_Facebook
Hope this helps.
A couple of weeks I had to do the same, and after and I came up with this. I needed it for an ajax login, but it mostly suits everyone needs.
This is the first step, it prompts the facebook login (if you are not already logged) and then redirect to your previously set uri.
$this->load->library('facebook_handler');
$this->facebook_handler->loginBegin($this->config->item('endpointfacebook'));
Facebook_handler in libraries folder
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Facebook_handler extends ML_index
{
var $scope = "email, user_about_me, user_birthday, user_hometown, user_website,read_stream, publish_stream, read_friendlists";
function __construct()
{ parent::__construct();
$this->CI =& get_instance();
$this->CI->config->load('mlogin_config'); //Config where I have the keys
if ( ! $this->CI->config->item('facebook_api_key') || ! $this->CI->config->item('facebook_api_key_secret') )
{
throw new Exception( "Your application id and secret are required in order to connect to {$this->providerId}.", 4 );
}
include_once(APPPATH.'libraries/Facebook/base_facebook.php'); //Place where I've situated the facebook libraries
include_once(APPPATH.'libraries/Facebook/facebook.php');
$this->fb = new Facebook( ARRAY( 'appId' => $this->CI->config->item('facebook_api_key'),'cookie'=>true, 'secret' => $this->CI->config->item('facebook_api_key_secret') ) );
$this->user = $this->fb->getUser();
}
/*The login process starts here, endpoint is the redirect_url for facebook*/
function loginBegin($endpoint)
{
$scope=$this->CI->config->item('facebook_scope');
if( isset( $scope ) && ! empty( $scope ) )
{
$this->scope = $scope;
}
$this->logout();
$url = $this->fb->getLoginUrl( array( 'domain'=>base_url(),'scope' => $this->scope, 'redirect_uri' => $endpoint,'display' => 'popup' ) );
redirect($url);
}
/*Function to get user data*/
function getUser(){
if ($this->user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $this->fb->api('/me');
return $user_profile;
} catch (FacebookApiException $e) {
error_log($e);
return false;
}
}else{
$this->output->set_output('no logueado');
}
}
/*Facebook logout, it destroys facebook sessions. I dont really use this*/
function logout(){
$this->fb->destroySession();
}
}
?>
The function to redirect to
function closewindowfacebook(){
$this->load->library('facebook_handler');
$userprofile=$this->facebook_handler->getUser();
if ($userprofile!=false){
$fb_uid = $this->facebook_handler->fb->getUser();
$fb_email=$userprofile['email'];
$fb_name=$userprofile['name'];
/*My function to connect to the website, that you'd do it yourself*/
//$this->auth->try_fb_login($fb_uid,$fb_email,$fb_name);
/*I use this to close the popup window*/
die('<script type="text/javascript">
window.opener.everythingready();
window.close();
</script>');
} else{
echo 'error ';
}
}
Ask if you have any further question

Categories