facebook how to delete cookie on logout - php

I am using the JS and PHP SDK and I can login a user successfully using facebook.
However logout doesnt seem to work (I can log a user out of my site but not out from facebook ).
Here is my logout code :
require_once('../libs/facebook/src/facebook.php');
$facebook = new Facebook( array (
'appId' => 'xxxx',
'secret' => 'xxxx',
'cookie' => true
)
);
$fb_key = 'fbsr_'.$facebookConfig['app_id'];
// set_cookie($fb_key, '', '', '', '/', '');
//$facebook->setSession(NULL);
$facebook->destroySession();
$facebook->getLogoutUrl();
$_SESSION = array();
session_unset();
session_destroy();
$files = array();
foreach ($_SESSION as $key => $value) {
$files[] = $key;
unset($_SESSION[$key]);
}
I have tried to use the following below to delete the cookie but I got an error message that setcookie is not a function
$fb_key = 'fbsr_'.$facebookConfig['app_id'];
setcookie($fb_key, '', time()-3600);
$facebook->destroySession();
Any suggestions will be appreciated.

For some reason I can't post a comment on your question, so here's an 'answer'.
Have you looked at this SO post?
Delete Facebook Session After Login with PHP SDK
More people are struggling on this, from what I've read. And nobody seems to know if there's a native function within the SDK. So unsetting it manually might be your best bet.

You need to append a user access token to the logout url.
Example from my app.
if($_GET['destroy']){
$facebook->destroySession();
}
$params = array( 'next' => 'https://apps.facebook.com/anotherfeed/?ref=logout&destroy=true', 'access_token' => $access_token);
$logout=$facebook->getLogoutUrl($params); // $params is optional.

Related

PHP API FACEBOOK - Users post to facebook page and personal wall

I created a contest where a submitted form will:
write a comment on the wall of Facebook staff and
write a comment on the wall of my page
I had no problems with step 1, but step 2 does not work. My code is as follows:
connect.php
<?php
//include the Facebook PHP SDK
include_once 'facebook.php';
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => 'CRYPT FOR THIS FORUM',
'secret' => 'CRYPT FOR THIS FORUM',
'cookie' => true
));
//Get the FB UID of the currently logged in user
$user = $facebook->getUser();
//if the user has already allowed the application, you'll be able to get his/her FB UID
if($user) {
//start the session if needed
if( session_id() ) {
} else {
session_start();
}
//do stuff when already logged in
//get the user's access token
$access_token = $facebook->getAccessToken();
//check permissions list
$permissions_list = $facebook->api(
'/me/permissions',
'GET',
array(
'access_token' => $access_token
)
);
//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'read_stream');
foreach($permissions_needed as $perm) {
if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
$login_url_params = array(
'scope' => 'publish_stream,read_stream',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
}
//if the user has allowed all the permissions we need,
//get the information about the pages that he or she managers
//id pag sposiamo รจ 494659577226200
$accounts = $facebook->api(
'/me/accounts',
'GET',
array(
'access_token' => $access_token
)
);
//save the information inside the session
$_SESSION['access_token'] = $access_token;
$_SESSION['accounts'] = $accounts['data'];
//save the first page as the default active page
//$_SESSION['active'] = $accounts['data'][0];*/
//redirect to manage.php
header('Location: manage.php');
} else {
//if not, let's redirect to the ALLOW page so we can get access
//Create a login URL using the Facebook library's getLoginUrl() method
$login_url_params = array(
'scope' => 'publish_stream,read_stream',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
//redirect to the login URL on facebook
header("Location: {$login_url}");
exit();
}
?>
newpost.php
<?php
//include the Facebook PHP SDK
include_once 'facebook.php';
//start the session if necessary
if( session_id() ) {
} else {
session_start();
}
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => 'CRYPT',
'secret' => 'CRYPT',
'cookie' => true
));
//get the info from the form
$parameters = array(
'message' => $_POST['message'],
'picture' => $_POST['picture'],
'link' => $_POST['link'],
'name' => $_POST['name'],
'caption' => $_POST['caption'],
'description' => $_POST['description']
);
//add the access token to it
$parameters['access_token'] = $_SESSION['active']['access_token'];
//build and call our Graph API request
$newpost = $facebook->api(
'/494659577226200/feed',
'/me/feed',
'POST',
$parameters
);
//redirect back to the manage page
header('Location: manage.php');
exit();
494659577226200 = FBPAGEID
PROBLEM IS '/494659577226200/feed', and error AuthCode 200...
You need to ask your user's to give your app manage_pages permission to post to their pages they manage on behalf of them. Check out their permissions doc here, See Page Permissions section.
Quoted from docs:
manage_pages
Enables your application to retrieve access_tokens for Pages and Applications that the user administrates. The access tokens can be queried by calling //accounts via the Graph API. This permission is only compatible with the Graph API, not the deprecated REST API.
See here for generating long-lived Page access tokens that do not expire after 60 days.
Once you get this permission, you can then make a wall post using page access token

Facebook PHP SDK - Web App is working on one machine but not any others?

I am on the verge of going crazy I think!
I am logged into my Personal Facebook account on my work machine and the app I am using works fine but on any other machine logged in as me, the app admin or anyone else the page just seems to keep on constantly refreshing with the state parameter in the url just whirring away and changing between page loads. (I have a laptop sitting on my desk, both using Firefox aswell)
I'm sure it was working on all machines that tested it the other day. Today it started with an error but I can't remember the error code but it was to do with the re-direct url not being owned by the domain but this doesn't seem to crop up now.
I am not the admin of the app either.
Here is the relevant code:
<?
error_reporting(0);
// Facebook PHP SDK
include_once "src/facebook.php";
// app id and seret from the facebook app
$appId = 'xxxxxxxxxxxxxx';
$secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => true,
));
//Facebook Authentication part
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => 'user_status,publish_stream,user_photos'
)
);
if ($user)
{
try
{
// page id and the feed we want
$user_feed = $facebook->api('PAGENUMBER/feed');
echo "<div id=\"graph\">";
$count = 0;
for ($i=0; $i<25; $i++)
{
// only want statuses - no videos, events, links etc.
if ($user_feed['data'][$i]['type'] == "status")
// just grabbing stuff and echoing it out
// blah blah blah
}
}
catch (FacebookApiException $e)
{
$user = null;
}
// close graph div
echo "</div>";
}
// if the user is not logged in then redirect to login page
if (!$user)
{
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
?>
This was a pain but took out the if ($user) and the try catch and the login redirect and all that seemed to work.

FACEBOOK GRAPH/rest api: how to LOGIN my OWN USER to update my STATUS with PHP

I want to update the status of a FAN-PAGE by PHP with the help of the Facebook graph api. google says: doesn't work.
Now I want to update my own user status by PHP. My main problem is how to login my own user to the graph api (with PHP), without using a browser and without funny PHP workarounds.
In both cases you need to get publish_stream permission http://developers.facebook.com/docs/authentication/permissions
This can be done with FB.login()
More information: http://developers.facebook.com/docs/authentication
After that you can just update status with graph api post: http://developers.facebook.com/docs/reference/api/post
my main problem is how to login my own
user to the graph api (with php),
without using a browser and without
funny php workarounds.
There's no way for you to act on behalf of a user (even your own user) without interacting with him through a browser at least once to get the offline_access.
How to get the offline_access permission and how to use it from there onward is explained in this answer.
EDIT:
Please read the comments! thanks #zerkms!
You need several things to update your facebook profile or a page's feed: a facebook application (client_id, client_secret), profile_id, and access_token (publish_stream, manage_pages, offline_access permissions)
You need offline_access because if not, then the access token will expire. If you've read that you don't need offline_access if you already have publish_stream specified, they just meant that you don't need it always.
To publish a post is easy:
$data = array(
'access_token' => $access_token,
'message' => 'status message',
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/{$profile_id}/feed");
Now how to get the profile_id and access_token, you can use my app post panda, or make your own script. I'll include it here:
# arvin castro
# http://codecri.me/
# January 16, 2011
$client_id = ''; # application id
$client_secret = ''; # application secret
$callbackURL = 'http://'; # the URL of this script
$extendedPermissions = 'publish_stream,manage_pages,offline_access';
session_name('facebookoauth');
session_start();
if(isset($_GET['logout']) and $_SESSION['loggedin']) {
$_SESSION = array();
session_destroy();
}
if(isset($_GET['signin'])) {
# STEP 1: Redirect user to Facebook, to grant permission for our application
$url = 'https://graph.facebook.com/oauth/authorize?' . xhttp::toQueryString(array(
'client_id' => $client_id,
'redirect_uri' => $callbackURL,
'scope' => $extendedPermissions,
));
header("Location: $url", 303);
die();
}
if(isset($_GET['code'])) {
# STEP 2: Exchange the code that we have for an access token
$data = array();
$data['get'] = array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'code' => $_GET['code'],
'redirect_uri' => $callbackURL,
);
$response = xhttp::fetch('https://graph.facebook.com/oauth/access_token', $data);
if($response['successful']) {
$var = xhttp::toQueryArray($response['body']);
$_SESSION['access_token'] = $var['access_token'];
$_SESSION['loggedin'] = true;
} else {
print_r($response['body']);
}
}
if($_SESSION['loggedin']) {
// Get Profile ID
$data = array();
$data['get'] = array(
'access_token' => $_SESSION['access_token'],
'fields' => 'id,name,accounts',
);
$response = xhttp::fetch('https://graph.facebook.com/me', $data);
echo '<pre>';
print_r(json_decode($response['body'], true));
echo '</pre>';
} else {
echo 'Sign in with Facebook';
}
?>
I'm using my cURL wrapper class, xhttp

Facebook Iframe application authentication?

I have developed a Facebook application that runs inside an iframe in the Facebook canvas. For it to work properly I request extended permissions from the user. If the user hasn't authorized the application I send him/her to a login page with the getLoginUrl() method in the PHP SDK.
It works, but it's not pretty. The method sends the user to a landing page before the authentication page. It looks like this:
When I click "Go to Facebook.com" I see the actual page for permission requests (I also get right to the permissions page if I print the url, copy it and enter it into a new browser window). How do I make Facebook skip this step when I do the redirect from an Iframe?
My code looks like this (using CodeIgniter and Facebook PHP SDK):
$this->facebook = new Facebook(array(
'appId' => '{MY_APP_ID}',
'secret' => '{MY_SECRET}',
'cookie' => TRUE,
'domain' => $_SERVER['SERVER_NAME']
));
$this->facebook->getSession();
try {
$this->me = $this->facebook->api('/me');
}
catch (FacebookApiException $e) {
$this->me = NULL;
}
if ( is_null($this->me) ) {
redirect($this->facebook->getLoginUrl(array(
'req_perms' => 'offline_access,read_stream,publish_stream,user_photos,user_videos,read_friendlists',
'next' => $this->config->item('base_url').'fblogin.php?redirect_uri='.$this->uri->uri_string()
)));
}
I think you need to redirect the parent frame (i.e. _top) rather than the iFrame itself?
The way I do it is set up an INDEX.PHP file with the following
//if user is logged in and session is valid.
if ($fbme){
//fql query example using legacy method call and passing
parameter
try{
$fql = "select name, hometown_location, sex,
pic_square from user where uid=" .
$uid;
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => 'http://apps.facebook.com/yoursite/'
);
$fqlResult = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
}
Then point your canvas url to http://yoursite.com/INDEX.php
The callback url in the above code which will be in INDEX.PHP sets where to look after permissions are granted.
FBMain.php looks like this
//set application urls here
$fbconfig['http://www.yoursite.com/iframeapp/YOURMAINPAGE.php/']
= "http://www.tyoursite.com/YOURMAINPAGE.php/";
$fbconfig['http://apps.facebook.com/CANVASBASEURL']
= "http://apps.facebook.com/CANVASBASEURL";
$uid = null; //facebook user id
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['APPID'],
'secret' => $fbconfig['SECRET'],
'cookie' => true,
));
//Facebook Authentication part
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms'=>'email,publish_stream,status_update,user_birthday,user_location'
)
);
$fbme = null;
if (!$session) {
echo "<script type='text/javascript'>top.location.href
= '$loginUrl';";
exit;
}
else {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href
= '$loginUrl';";
exit;
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
} ?>
Hope its a little clearer. It took me a while to figure it out, but I got there, thought I would help.

Slow script...want to display iframe

I have a php script that is slow, but must complete in it's entirety. At the end of the script it redirects to a url.
I am thinking of somehow displaying an iframe while the scirpt is loading so visitors don't leave the page. What is the best way of doing this? With the iframe there would be no need to redirect after the completion of the script.
<?php
require_once('config.php');
if(!$_SESSION['init']){
die;
}
unset($_SESSION['init']);
require_once('facebook.php');
$data = loaddata();
$facebook = new Facebook(array(
'appId' => $fbappid,
'secret' => $appsecret,
'cookie' => true,
));
$friendsdate = $facebook->api('/me/friends');
if($friendsdate && $friendsdate['data'] && count($friendsdate['data'])){
$friends = array();
foreach($friendsdate['data'] as $f){
$friends[] = $f['id'];
}
sleep(3);
$session = $facebook->getSession();
$params = array('name' => $data['name'],
'start_time' => $data['start_time'],
'end_time' => $data['end_time'],
'description' => $data['description']);
if($data['source']){
$params['source'] = '#'.realpath('image/'.$data['source']);
$facebook->setFileUploadSupport(true);
}
$result = $facebook->api('/me/events', 'POST', $params);
sleep(4);
$eid = $result['id'];
$params = array(
'access_token' => $facebook-> getAccessToken(),
'eid' =>$eid,
'api_key' => $fbappid,
'uids'=> implode(',', $friends),
'format'=>'json-strings',
'personal_message'=> $data['personal_message']
);
$url = 'https://api.facebook.com/method/events.invite';
$facebook->setFileUploadSupport(false);
$result = $facebook->makeRequest($url, $params);
}
header('Location: '.$data['url']);
The proper way to do what you want is to use ajax.
Main page:
Shows some sort of "working" message in a div.
On load, javascript calls out to the worker page.
On response, the javascript replaces the "working" div with the response from the worker page.
Worker page:
Does your long php work.
Displays whatever you think is appropriate.
Here is a tutorial on AJAX to get you started: http://www.w3schools.com/ajax/default.asp
Yes it'll work, facebook api gets very slow at times, so you can use iframe or ajax.
For iframe - just replace the final header('location:... with javascript redirect
echo "<script>self.parent.location = 'http:// ... ';</script>";
Also you must do session_commit somewhere at the script's top, if you're using php sessions because otherwise the iframe could lock the main script. AJAX... not really necessary.

Categories