Facebook Logout Using PHP - facebook

I am using facebook's PHP SDK to log user into my website.
Now when I click on logout button, it successfully clears the session. When he again clicks on login with facebook button, he automatically logs into my website with the same facebook account he used before logging out instead of showing logging in page.
<?php
session_start();
/*
echo "before logout.</BR></BR>";
echo 'id: ' . $_SESSION['id']."</BR></BR>";
*/
require_once 'Facebook/autoload.php';
require_once 'Facebook/Facebook.php';
$config = array();
$config['appId'] = 'My Appid';
$config['secret'] = 'My Secret';
$config['fileUpload'] = false;
$fb = new Facebook\Facebook([
'app_id' => 'My Appid', // Replace {app-id} with your app id
'app_secret' => 'My Secret',
'default_graph_version' => 'v3.2',
]);
//$facebook = new Facebook($config);
//$token = $fb->getAccessToken();
//$accessToken = $fb->getAccessToken(); // Not working - Error showing - undefined method
//echo $_SESSION['fb_access_token']; - This contains some long access token
unset($_SESSION['id']);
//echo $accessToken;
/*
echo "after logout.</BR></BR>";
echo 'id : '. $_SESSION['id']."</BR></BR>";
*/
//$url = 'https://www.facebook.com/logout.php?next=https://rocketevent.in&access_token='.$_SESSION['fb_access_token']; - going to facebook page, not returning back
//echo $url;
session_destroy();
$fb->getLogoutUrl();
//header('Location: '.$url);
//header("Location: ../../index.php");
?>

You should provide your 'app_id' and 'app_secret'. You can get these from https://developers.facebook.com

Related

How to fix Facebook App Login Error

I am new to Facebook App Developing. I am trying to use facebook login. But this error is popping up. 1 This is my code.
<?php
session_start();
require_once 'Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '240676292969845', // Replace {app-id} with your app id
'app_secret' => '111111111111111111111',
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('https://warunaphotography.com/fb-callback.php', $permissions);
echo 'Log in with Facebook!';
?>
This is the facebook app settings.
3
Please help me.

Facebook Canvas App Login for new Users

i have created a facebook app and it works well for new users if they start the app with the direct server link (https://www.mydomain.com/app/index.php) and use the login button.
But if they try to use the app within facebook (https://apps.facebook.com/myapp) as a canvas app(for the first time) then they see the "landing" page of my app and the log in button. But if they click on it, an errormessage appears, that the content of the iframe couldn't be displayed. If they start the app in a new tab, then the login process works. (see the error below, sorry it's german, maybe you are familiar with this type of error message?)
It would be desirable if the new user could use the login link in the canvas app.
How can this be achieved? My index.php looks like this: (i am using the facebook SDK)
<?php
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?php
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
echo "Name: " . $user_profile['name'];
} catch(FacebookApiException $e) {
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
}
?>
</body>
</html>

Using Facebook Object in Multiple PHP Files

I am creating a Facebook Application containing multiple PHP pages. If I reinstantiate Facebook objects in all the files I get an Error Invalid OAuth access token signature.
I have tried a number of alternatives, also the $facebook->getSession() function doesn't work in the new framework and is deprecated.
So I tried to keep the access token in the session and use the same access token in my next PHP file's Facebook object.
On my first page i Have instantiated my App using:
$app_id = "107684706025330";
$app_secret = "__SECRET__";
$my_url = "http://www.sentimentalcalligraphy.in/wp-content/then_n_now/";
$config = array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true,
);
session_start();
$facebook = new Facebook($config);
$access_token = $facebook->getAccessToken();
echo $access_token;
$_SESSION['fob'] = $access_token;
On the next PHP file were I need to use the Facebook object for the second time:
$config = array(
'appId' => '107684706025330',
'secret' => '__SECRET__',
);
$facebook = new Facebook($config);
$access_tocken = $_SESSION['fob'];
echo $access_token;
$facebook->setAccessToken($access_token);
I still get an error that the access token is not valid. How am I supposed to use this. I need to use the following code in my second PHP file:
$friends = $facebook->api('/me/friends','GET');
Thanking you in Advance,
Nasir
I have a some code for Facebook API. I want to share with you.
// App user account and password
$app_id = 'blabla';
$app_secret = 'blabla';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
// Get User ID
$user = $facebook->getUser();
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
$access_token = $facebook->getAccessToken();
if(isset($_GET["code"])){
// Get our app user feed
$user_profile_feed = $facebook->api('/me');
// Insert user id into users table while user login our app
// We have to control user who inserted our users table after before
$query_is_user = mysql_query("SELECT * FROM `users` WHERE `user_id` = ".$user_profile_feed['id']) or die("hata 1");
$count = mysql_num_rows($query_is_user);
if($count == 0) {
mysql_query("INSERT INTO `users`(`user_id`) VALUES (".$user_profile_feed['id'].")") or die("hata 2");
echo '<script language=Javascript>alert("Uygulamamiza Basariyla Giris Yaptiniz...");</script>';
}
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . "http://apps.facebook.com/machine_learning/"
. "&client_secret=" . $app_secret . "&code=" . $_GET["code"];
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
mysql_query("UPDATE users SET access_token='$params[access_token]' WHERE user_id='$user_profile_feed[id]'") or die("hata 4");
}
$url = "https://graph.facebook.com/oauth/authorize?"
."client_id=262609310449368&"
."redirect_uri=http://apps.facebook.com/machine_learning/&scope=read_stream";

$facebook->getSession() in Facebook page iframe app/tab only works when app admin logged in

I am developing some custom iframe/canvas pages (or now known as "apps") for a Facebook business page. For my purposes, I would like to pull the users first and last name that is currently logged in (and currently likes the page) and output it on the page. This script works just fine when I am logged in as the app admin, but when I try login as my personal account or a a couple of my friends account - it seems that $session is null. Why is this happening and how do I fetch a first and last name without having the user go through any additional authentication?
<?php
require_once '../db/connect.php';
require_once '../../lib/facebook.php';
$signed_request = $_REQUEST["signed_request"];
$secret = "***********************************";
$facebook = new Facebook(array(
'appId' => '**************',
'secret' => $secret,
'cookie' => true
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
echo "\$session is not null!";
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
echo $me['name'];
?>
Unfortunately, this is not possible (reference):
As with a Canvas Page, you will not
receive all the user information
accessible to your app in the
signed_request until the user
authorizes your app.
So you need the user to authorize your application first, this can be found here:
<?php
$app_id = YOUR_APP_ID;
$canvas_page = YOUR_CANVAS_PAGE_URL;
$auth_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page);
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
echo ("Welcome User: " . $data["user_id"]);
}
?>
After authorizing your application and getting the User ID, the process is trivial I suppose.

Username not displayed in Facebook Hello world application

I am new to creating a facebook application and hence started out with a simple Hello World Application. But When I try to display my Name, it is not displayed.
This is my code:
<?php
require_once 'facebook.php';
$api_key = 'mykey';
$secret = 'mysecretkey';
$facebook = new Facebook($api_key, $secret);
$user = $facebook->require_login();
$fbml = "<h2>Hello world, my name is <fb:name uid='<?php echo $fb_user;?>' useyou='false' />,"
. "welcome to my first facebook application!</h2>";
echo $fbml;
?>
The output in my facebook app is,
Hello world,my name is,welcome to my first facebook application!
My name is missing here.
And If I add the code given below,to display the friend's list,
$friends = $facebook->api_client->friends_get();
echo "<pre>Friends:" . print_r($friends, true). "</pre>";
I get the error message,
Warning: fopen() [function.fopen]: php_network_getaddresses: getaddrinfo failed:
No such host is known.
in C:\Documents and Settings\256148\My Documents\ide\xampplite\htdocs\facebookApp\facebookapi_php5_restlib.php on line 1755
Warning: fopen(http://api.facebook.com/restserver.php) [function.fopen]:
failed to open stream: php_network_getaddresses: getaddrinfo failed:
No such host is known. in C:\Documents and Settings\256148\My Documents\ide\xampplite\htdocs\facebookApp\facebookapi_php5_restlib.php on line 1755
Please guide me.
I have found a solution for my problem. I had to set the connect url in the application setting to my canvas callback url and created a cross domain communication channel file as given in this tutorial. This tutorial is really very helpful and explains in detail about creating a simple facebook app.
But still I get the Network error when I use $facebook->api_client->friends_get();
FBML Facebook Application
First, try using the following code for authentication process (applogin.php):
<?php
require_once "facebook.php";
require_once "config.php";
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_API_SECRET,
'cookie' => true
));
$session = $facebook->getSession();
$params = array(
'canvas' => 1,
'fbconnect' => 0,
'next' => URL_CANVAS,
'cancel_url' => 'http://www.facebook.com/',
'req_perms' => 'publish_stream, status_update, offline_acces'
);
$login_url = $facebook->getLoginUrl($params);
// if not logged in, redirec to login page
if (!$session) {
echo '<fb:redirect url="' . $login_url . '" />';
exit;
} else {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$access_token = $session['access_token'];
} catch (FacebookApiException $e) {
echo 'Error';
exit;
}
}
?>
Here's the config.php:
<?php
// Facebook
define('FB_APP_ID', '');
define('FB_API_SECRET', '');
define('URL_CANVAS', 'http://apps.facebook.com/YOURAPP/');
define('URL_CALLBACK', 'http://FB.YOURCALLBACKURL.COM/YOURAPP/');
?>
And finally your index.php
<?php
require_once dirname(__FILE__) . "/applogin.php";
// using Graph API
echo $me['name'];
?>
<!--// some FBML //-->
<fb:bookmark />
<h2>Hello world, my name is fb:name uid='<?php echo $uid;?>' useyou='false' />
welcome to my first facebook application!</h2>
Hope this will help you write your own Facebook application.