How to log out of facebook - php

I have the following script which will allow a user to login to my website using their facebook account, request the appropriate permissions, and if accepted, it will post a message on a wall:
<?php
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'removed for security reasons',
'secret' => 'removed for security reasons',
'cookie' => true,
));
$session = $facebook->getSession();
if ($session) {
if (isset($_GET[id])) {
$post = $facebook->api("/" . $_GET['id'] . "/feed", "POST", array('message' => 'Hello!'));
echo 'A message has been posted on your friends wall';
} else {
$friends = $facebook->api('/me/friends');
foreach ($friends as $key=>$value) {
echo 'You have ' . count($value) . ' friends<br />';
foreach ($value as $fkey=>$fvalue) {
echo 'friend id = ' . $fvalue[id] . ' - friend name = ' . $fvalue[name] . ' - post message<br />';
}
}
}
} else {
$loginUrl = $facebook->getLoginUrl(array(
'req_perms' => 'publish_stream',
'next' => 'http://'.$_SERVER['SERVER_NAME'].'/stage0.php',
'cancel_url' => 'http://'.$_SERVER['SERVER_NAME'].'/cancel.php',
));
header('Location: '.$loginUrl);
}
?>
I then have the following script to log the user out:
<?php
error_reporting( E_ALL | E_STRICT );
ini_set('display_errors', 1);
?>
<?php
session_start();
?>
<html>
<head>
<title></title>
<?php
$_SESSION = array();
session_destroy();
?>
<meta http-equiv="refresh" content="0;index.php">
</head>
<body>
<h1>logout</h1>
</body>
</html>
This clears the sessions I created, but it does not log them out of facebook at all. How do I clear the sessions I create and also log them out of facebook?

Recommended way to log out a user from both your application and Facebook, is to call the logout feature of the javascript SDK.
logout
check : http://developers.facebook.com/docs/reference/javascript/FB.logout/

/* Use access token i.e. $_SESSION['facebookAccessToken']*/
function logoutUser($sessionKey)
{
include_once 'facebook.php';
$facebook = new Facebook( array('appId'=>FACEBOOK_APP_ID , 'secret'=>FACEBOOK_APP_SEC , 'cookie' => true));
$logoutUrl = $facebook->getLogoutUrl(array('next' => BASE_URL , 'session_key' => $sessionKey));
return $logoutUrl;
}
$access_array = explode('|' , $_SESSION['facebookAccessToken']);
$sessionKey = $access_array[1];
$redirectUrl = logoutUser($sessionKey);
header('Location: '.$redirectUrl );

Use this as your logout URL:
Logout
And this for your code:
if(isset($_GET['action']) && $_GET['action'] === 'logout'){
$facebook->destroySession();
}
This will log the user out of the app, rather than facebook itself, logging out of facebook altogether, which is not recommended, as it will distress some users, add this to your session where if($session) { is
$logoutUrl = $facebook->getLogoutUrl();
then for your logout URL, use:
Logout

Facebook Oauth Logout

Related

Not getting any information from Facebook login

I'm implementing Facebook login on my website, it's working without error but ultimately I'm not able to get any information of a user.
I've following code.
<?php
include 'library.php';
include 'facebook.php';
$app_id = "XXXXXXXXX";
$app_secret = "XXXXXXXXX";
$site_url = "XXXXXXXXX";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
$user = $facebook->getUser();
if($user){
try{
$user_profile = $facebook->api('/me');
}catch(FacebookApiException $e){
$user = NULL;
}
}
if($user){
$logoutUrl = $facebook->getLogoutUrl();
}else{
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email',
'redirect_uri' => $site_url,
));
}
if($user){
Echo "Email : " . $user_profile['email'];
}
$user_fbid = $fbuser;
$user_email = $user_profile["email"];
$user_fname = $user_profile["first_name"];
$user_image = "https://graph.facebook.com/".$user_fbid."/picture?type=large";
echo $loginUrl = $facebook->getLoginUrl( array('scope' => 'email,read_stream'));
What's wrong with this? Can anyone point out? I've gone though a number of questions but none of them seemed to work for me & I finally ended up posting a question myself.
EDIT
When asking for login, it displays permissions correctly like email, friend list, your likes etc. So basically it's asking correctly & even though I approve, information is not coming up. Tried with a couple of users.
EDIT
Try use this code, and work from there ... That's how I figured it out
<HTML>
<BODY>
<?php
require_once("fb/facebook.php");
$config = array(
'appId' => 'XXXXX',
'secret' => 'XXXXXXX',
'fileUpload' => false, // optional
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$uid = $facebook->getUser();
$loginParams = array('scope' => 'email');
$loginUrl = $facebook->getLoginUrl($loginParams);
$logoutParams = array('next' => 'http://fb_logouturi');
$logoutUrl = $facebook->getLogoutUrl($logoutParams);
echo $uid . '</br>';
echo 'Login:' . $loginUrl . '</br>';
echo 'Logout:' . $logoutUrl . '</br>';
if($uid) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$user_profile = $facebook->api('/me','GET');
echo "</br>First Name: " . $user_profile['first_name'];
echo "</br>Last Name: " . $user_profile['last_name'];
echo "</br>Email: " . $user_profile['email'];
echo "</br>Gender: " . $user_profile['gender'];
echo "</br><img src='http://graph.facebook.com/" . $uid ."/picture?type=large'>";
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, print a link for the user to login
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
}
?>
</BODY>
</HTML>

session variables not work after redirect facebook page

Here is my below code related to upload image on facebook TimeLine but i have issue $_SESSION variable not keep store value after redirect form facebook.
<?php
session_start();
require 'facebook.php';
echo $_SESSION['uploadimage'] = $_POST['img_url'];
echo $_SESSION['return_url'] = $_POST['return_url'];
//die(); if I remove comment from die() function then session variable echo
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
));
// Get User ID
$user = $facebook->getUser();
$_SESSION['id'] = $user;
$loginUrl = $facebook->getLoginUrl();
//$_SESSION['id'];
?>
<?php
// Login or logout url will be needed depending on current user state.
if (isset($_GET['upload'])) {
echo "yes";
if ($_SESSION['id']) {
$facebook->setFileUploadSupport(true);
$args = array(
'message' => 'by http://thecodedeveloper.com'
);
copy($_SESSION['uploadimage'], 'tmp/file.jpeg');
$args['image'] = '#' . realpath('tmp/file.jpeg');
$data = $facebook->api('/me/photos', 'post', $args);
unlink('tmp/file.jpeg');
//assigning users to tag and cordinates
$argstag = array(
'to' => $user
);
$argstag['x'] = 40;
$argstag['y'] = 40;
$datatag = $facebook->api('/' . $data['id'] . '/tags', 'post', $argstag);
// echo 'Success! Check your facebook wall now';
header("Location:" . $_SESSION['return_url']);
} else {
header('Location:' . $loginUrl . '&scope=user_photos,publish_stream');
}
}
?>
Add session_start(); on top of your PHP code.
<?php
session_start(); //<-- Here
require 'facebook.php';
ob_start();
session_start();
require 'facebook.php';
$img_url = isset($_POST['img_url'])?$_POST['img_url']:'';
$return_url = isset($_POST['return_url'])?$_POST['return_url']:'';
if(!empty($img_url){
echo $_SESSION['uploadimage'] = $img_url;
}
if(!empty($return_url)){
echo $_SESSION['return_url'] = $return_url;
}

Facebook publish_stream code ends up in a loop

I have the following code which works fine as long as in a previous part of the application, the user accepts the applications request to publish_stream.
# The facebook library
require_once("/var/www/facebook-php-sdk-master/src/facebook.php");
# Create facebook object
$config = array();
$config['appId'] = 'appId_here';
$config['secret'] = 'secret_here';
$config['fileUpload'] = false; // optional
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if ($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
#check permissions
$api_call = array(
'method' => 'users.hasAppPermission',
'uid' => $user_id,
'ext_perm' => 'publish_stream'
);
#set to true if true...
$can_offline = $facebook -> api( $api_call );
#is it true?
if( $can_offline ) {
$post = array(
'message' => 'post_a_message'
);
$facebook->api('/' . $_GET["id"] . '/feed', 'POST', $post);
} else {
// can't post message - don't have permission
}
} catch (FacebookApiException $e) {
error_log($e);
exit;
}
} else {
error_log("user not logged in");
exit;
}
To try to resolve this, I attempted to insert the following code into the else statement which currently in the code above only contains the comment // can't post message - don't have permission
The code I tried to insert into that else was this:
$loginUrl = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
header("Location: ".$loginUrl);
That works as long as the user accepts to allow my app to publish_stream. However, if the user does not accept, my app will keep asking the user to accept publish_stream. How do I stop that loop from happening if the user decides not to accept?
As far as i remember, $facebook -> getLoginUrl can take parameter cancel_url, which contains the link, where user should be redirected if he doesn't give your app permissions.
So the code will be something like this
$login_url = $facebook -> getLoginUrl( array(
'scope' => 'publish_stream',
'cancel_url' => YOUR_LINK_HERE
));
Here is the working code : Please check it :
Page name : events.php
You can see $redirect_uri = https://localhost/facebook_page/events.php it is returning back to same page.
<?php
$facebook_appid = "your appid"; // Facebook appplication id
$facebook_secret = "your app secret"; // Facebook secret id
$redirect_uri = "https://localhost/facebook_page/events.php"; // return url to our application after facebook login ## should be SAME as in facebook application
$scope = "publish_stream"; // User permission for facebook
$profile_id = "profile_id";// Where do you want to post it(profile id - It is a number)
$code = $_REQUEST["code"]?$_REQUEST["code"]:"";
if(empty($code)) {
$_SESSION['state'] = rand(); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=". $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri) . "&state=". $_SESSION['state'] . "&scope=".$scope;
header("location:".$dialog_url);
}
if($_SESSION['state'] && ($_SESSION['state'] == $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri). "&client_secret=" . $facebook_secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
?>
<!-- Here you can use
message, picture, link, name, caption, description, source, place, tags
as input fields-->
<form enctype="multipart/form-data" method="POST" action="https://graph.facebook.com/<?php echo $profile_id;?>/feed?access_token=<?php echo $access_token; ?>">
<input type="text" name="message" value="test" />
<input type="submit" name="submit" value="Submit" />
</form>
You can post it using jquery also.
I use the following code to check if the user has allowed publishing permisions or not:
$permissions = $facebook->api('me/permissions');
if( array_key_exists('publish_stream', $permissions['data'][0]) ) {
//Continue with posting on users wall
} else {
//Continue without posting on users wall
}

Post a Link from PHP

I have this script:
This code should post a Text and a Link to a WebSite
<?
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('facebook.php');
$c = array(
'appId' => '4102137023*****',
'secret' => '*****c4a60cb08*****7c0333*****',
);
$facebook = new Facebook($c);
$uid = $facebook->getUser();
echo "Userid: " . $uid;
echo "<BR>";
?>
<html>
<head></head>
<body>
<?
if($uid){
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'angel-craft.de',
'message' => 'Wenn ihr das hier seht freut euch auf ein Game'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array(
'scope' => 'publish_stream'
));
echo 'Please login.';
echo $e->getType();
echo $e->getMessage();
}
// Give the user a logout link
echo '<br />logout';
} else {
// No user, so print a link for the user to login
// To post to a user's wall, we need publish_stream permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
echo 'Please login.';
}
?>
</body>
</html>
This should post a link with a text
but the Userid($uid) stays empty.
And YES this is the Demo script from FB dev.
I've used this successfully.
<?php
require 'src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '-----',
'secret' => '-----',
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$Name = $me['first_name'];
$properties = array(
array(
'text'=>'Property Link',
'href'=>'http://www.yahoo.com'
),
array(
'text'=>'Property Link',
'href'=>'http://www.yahoo.com'
)
);
// Link that is adjacent to "Like" and "Comment" at the very bottom of the post.
$action_links = array(
'name'=>'Test',
'link'=>'http://www.yahoo.com'
);
// Dictates who can see the post.
$privacy = array(
'value'=>'ALL_FRIENDS'
);
// api('/me/feed', 'post',... = Wall Post.
$wallPost = $facebook->api('me/feed', 'post', array(
'message'=> 'Testing',
'link'=> 'http://www.yahoo.com',
'properties'=>$properties,
'actions'=>$action_links
)
);
} catch (FacebookApiException $e) {
error_log($e);
}
}
$par = array();
$par['req_perms'] = "email, publish_stream";
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl($par);
}
?>
I found the bug, The cert was old. Thanks to all :)

APP on redirect_url shows blank page

I have a Facebook PHP SDK APP in development phase and i'm stuck on something...
The logic of the APP is this:
first the user have to like the page (app is on this) // works very well :)
after that comes the permissions request
if permission is granted: the app_data variable is pass through and the user recieves a picture.
app_data variable is necessary because, if the user clicks the app after permission granted again, it gets new picture automaticly. with the app_data don't.
my problem is this link:
$params = array(
scope => 'publish_stream,user_photos',
redirect_uri => 'http://www.facebook.com/XXXXX?sk=app_YYYYYY&app_data=1'
);
Accept
If i click on it, the app shows blank page, and nothing happening... :(
On direct call, that app runs without any error.
Can someone help me out?
// sorry for my english...
Thank you!
and the whole index.php is:
this is the whole index.php:
<?php
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxxxx',
'secret' => 'yyyyy',
'baseUrl' => 'http://hosting.address/',
'appBaseUrl' => 'http://apps.facebook.com/app-name/',
'fileUpload' => 'true',
));
// Get User ID
$user = $facebook->getUser();
$params = array(
scope => 'publish_stream,user_photos',
redirect_uri => 'http://www.facebook.com/xxxxx?sk=app_yyyyy&app_data=1'
);
$signed_request = $facebook->getSignedRequest();
$app_data = $signed_request["app_data"];
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>the title</title>
<style>
a:link {color:#ffffff;}
a:visited {color:#ffffff;}
a:hover {color:#ececec;}
a:active {color:#1f1f1f;}
a:link {text-decoration: none}
</style>
</head>
<body>
<?php if ($user){
try {
$user_profile = $facebook->api('/me');
$likes = $facebook->api("/me/likes/123123123"); //page ID
if( !empty($likes['data']) ){
$scope = 'publish_stream,user_photos';
$scope_params = explode(',',$scope);
$permissions = $facebook->api("/me/permissions");
if( array_key_exists('publish_stream', $permissions['data'][0]) && array_key_exists('user_photos', $permissions['data'][0]) && isset($app_data)) {
$file = "1.jpg";
$message = 'bla bla';
$ret_obj = $facebook->api('/me/photos', 'POST', array(
'source' => '#' . $file,
'message' => $message,
)
);
echo "<img width=\"520px\" src=\"1.jpg\" />";
} else {
?>
accept</td>
deny</td>
<?
}
}else{
echo "<img width=\"520px\" src=\"no-fan.jpg\" />";
}
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
if ($user) {
} else {
$loginUrl = $facebook->getLoginUrl($params);
echo '<script type="text/javascript">top.location.href = "'.$loginUrl .'";</script>';
}
?>
</body>
</html>
I've had this before when I was delving into the world of Facebook apps.
What I eventually done was for my redirect_uri I used a page on my domain, e.g. https://domain.com/facebook/redirect.php and in redirect.php I would have:
// user didn't give app permissions
if (isset($_GET['error_reason']))
{
header( 'Location: http://www.facebook.com/FANPAGE' ) ;
}
else
{
header( 'Location: http://www.facebook.com/XXXXX?sk=app_YYYYYY' ) ;
}

Categories