I started playing around with the fb api a couple of days ago. I am using the fb php-sdk to authenticate users with facebook on my site. I use the following piece of code which works, but intermittently and I cant seem to figure out why.
<?php
session_start();
require './library/facebook.php';
include './library/fb_keys.php';
// Create app instance
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
// Get User ID
$user = $facebook->getUser();
//Check Access token
if ($user) {
try {
// Proceed with logged in user.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//error_log($e);
$user = null;
}
}
// Login or logout based on user state
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('scope' => 'status_update, publish_stream', 'redirect_uri' => 'http://webaddress.com/web/'));
}
?>
This is really straightforward piece of code that I got from the https://github.com/facebook/php-sdk/.
I usually can't log in when I clear all my cookies and/or session is cleared. but once I log on to the facebook.com site all seems to work again. So it indicates that I am missing something with regard to setting the session or cookies.
Any help will be appreciated.
I guess by not working you mean that user isn't redirected to the login page?
You do get the loginUrl but you're not redirecting user there.
This can be easly done with adding the following code after $loginUrl line:
print '<script language="javascript" type="text/javascript"> top.location.href="'. $loginUrl .'"; </script>';
If I'm wrong please tell me exactly what you mean under "can't log in", what stops you etc.
Related
I have just started mingling with facebook's php sdk, but to no avail. Although php works fine for all the other stuff on my ubuntu instance, facebook's php sdk doesn't (i.e. php code is not executed). All dependencies (only curl and json) are enabled and working.
I tried to look into /var/log/apache2/error.log but it seems that the file is empty - but maybe I'm not looking in the correct place.
So my question is: what would be the steps for me to debug this problem! Thanks for helping a noob!
Here is the boilerplate index.php code for from facebook:
<?php
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxx',
));
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$statusUrl = $facebook->getLoginStatusUrl();
$loginUrl = $facebook->getLoginUrl();
}
// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');
?>
When I run this code, and my cookies have been cleared and I am not logged into facebook. It directs me to facebook and I log in but when it brings me back to my page it is the same, where as it should be show me profile pic and so on...
I seem to have narrowed down the problem of the return statement of the $user because it returns a 0. I have stared at this code for a long time and I havent found what I am doing wrong.
What do i need to change to get it so that When i return from logging in from facebook it will show the profile pic and so on...
<?php
require_once 'libs/facebook.php';
require 'connections/connection.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxx',
));
// Get User ID
$user = $facebook->getUser();
echo $user;
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
echo $user;
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
//$logoutUrl = $facebook->getLogoutUrl();
$logoutUrl = $facebook->getLogoutUrl(array('next' => ($fbconfig['baseurl'] . 'logout.php')));
} else {
$statusUrl = $facebook->getLoginStatusUrl();
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'user_about_me',
'scope' => 'read_friendlists'
));
}
?>
Not to worry my friend, you are not doing anything wrong. I'm having same issue with my DEMO application which was running alright till yesterday.
I'm sure you are having issue with getting access token as well. I think issue is with PHP SDK only.So probably will be fixed in some time.
SOLUTION : This worked for me after trying for many solutions for this issue.
In base_facebook.php file, find the makeRequest() method and check for following Line.
$opts = self::$CURL_OPTS;
Immediately following it, add this line
$opts[CURLOPT_SSL_VERIFYPEER] = false;
More details can be found here - http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/
I am trying to add Facebook login to my web site.
What I have done?
Created APP on Facebook as Website with Facebook Login
Sandbox mode is off
APP is set to work on localhost.
What is the problem?
I keep getting $user variable's value as 0
example.php in Facebook PHP SDK works just fine!
I can see my APP when I visit Facebook -> Privacy Settings -> Apps. No matter if I login with my login.php or example.php of Facebook PHP SDK, the app seems to be added just the same. However while example.php can retrieve data from facebook, login.php can't.
I copy and paste the codes from example.php to my login.php page (please check the code below).
Here is my code (login.php);
require_once('system/api/facebook/facebook.php');
$facebook = new Facebook(array(
'appId' => '123456',
'secret' => 'abcde12345',
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
if (!$user) echo 'Login';
echo '<pre>';
var_dump($user);
echo '</pre>';
Can someone please tell me what is the difference between my login.php and example.php? I also Googled and searched here without finding any info which was helpful.
I've recently been trying to get my app working with the PHP SDK 3.0 and been having some trouble with it seeing that I am actually logged in. I have the "example.php" from the 3.1.1 download that doesn't acknowledge that I'm logged in. The file "with_js_sdk.php" also doesn't acknowledge that I'm logged in when you first run it. After it has been run, however both that file and the "example.php" will see that I'm logged in. Once I log out, "example.php" doesn't work and "with_js_sdk.php" fails on the first run, but all subsequent runs both files (and some other files I'm testing this with) will all authenticate correctly. When not working, all files give an "OAuthException" with the message: "An active access token must be used to query information about the current user." even when I'm logged in. So my question is, is there something in the "with_js_sdk.php" that I can set in my other files? I'm guessing it has something to do with the "oauth:true" in that file from what I've read, although I'm not a Facebook coding expert so I'm not sure. And I have an iframe app, so I don't have the "FB.init" part in my application (that worked incidentally until the change in the sdk). Here's the minimum code I'm testing that's giving the error:
<?php
require '../src/facebook.php';
$facebook = new Facebook(array(
'appId' => '11111111111111111',
'secret' => 'abcdefghijk etc...',
'cookie'=>true
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
The getuser always comes back correctly, but the $facebook->api('/me') call always fails until I run a file with the fbml in it. And before you ask, yes I changed the appID and secret in the files. Thanks.
Darryl
Instead of me pass $user. Eg:
$user_profile = $facebook->api('/'.$user);
I had the same problem and suffered for the longest time, and solved it by simply getting the new PHP SDK files from https://github.com/facebook/php-sdk.
Reference: http://developers.facebook.com/docs/reference/php/
Have you tried print_r($user_profile) to see what comes out? Also, the cookie parameter is not used with the latest SDK.
You have to be aware of the scope of variables, $user_profile will be only inside the scope of you if statement, so If you want to access from outer scope it will be not available remember you can always declare your variable outside and then initialize it, this way it will be available through your php file.
?php
require '../src/facebook.php';
$facebook = new Facebook(array(
'appId' => '11111111111111111',
'secret' => 'abcdefghijk etc...',
'cookie'=>true
));
// See if there is a user from a cookie
$user = $facebook->getUser();
$user_profile; // variable being declare outer scope
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
THIS WORKS FOR ME
$user_profile = $facebook->api('/'.$user);
And here is my full php fb connect script example: `
$fbconfig['appid' ] = " id ";
$fbconfig['secret'] = " secret ";
$fbconfig['appBaseUrl'] = "https://apps.facebook.com/ example /";
$user = null; //facebook user uid
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
$user = $facebook->getUser();
// We may or may not have this data based
// on whether the user is logged in.
// If we have a $user id here, it means we know
// the user is logged into
// Facebook, but we don’t know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown'
)
);
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$me = $facebook->api('/'.$user);
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
d($e); // d is a debug function defined at the end of this file
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
//get user basic description
$me = $facebook->api("/$user");
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
if (isset($_GET['code'])){
header("Location: " . $fbconfig['appBaseUrl']);
exit;
}`
Have a nice day ! :)
when the token is invalid, kick off the authentication flow.
also, to get jssdk to work with php sdk v3.x, make sure you have upgrade your js sdk code to use OAuth 2.0.
you are missing with something.To have an active access token you must present it inside a session variable.And you are not even creating a session in your code.
YOU MUST HAVE AN ACCESS TOKEN FIRST
try this->
$access_token =$facebook->getAccessToken();
if ($user) {
if( session_id() ) {}
else {session_start();}
Now you should store $_SESSION['access_token']=$access_token ; for later use.
I'm tired of digging through tons of tutorials/documentations which don't help me at all.
What I have now (everything is placed inside admin control panel):
If user is logged on correct account (administrator of page with granted rights), everything works fine, post on page is posted as impersonated site.
If he is logged on other account, nothing happens. Site redirects him to his wall.
If he isn't logged on any account, he's redirected to facebook login - if he logs onto correct account, he returns to acp (it's bad solution, because it'll clear his form)
I want to achieve:
If logged in, everything as it was
Else popup with login to specific (correct) account
At the moment I'm using only PHP, but solution with JS is permitted.
My code:
<?php
/*(...)*/
$facebook = new Facebook(array(
'appId' => $apiid,
'secret' => $secret,
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
if($me) {
//In order to post to the page later on we need to generate an Access Token for that page, to do this we get me-accounts in the following api call
$accounts = $facebook->api('/me/accounts');
//Loop through the array off accounts to find the page with a matching ID to the one we need
foreach($accounts['data'] as $account){
if($account['id'] == PAGEID){
$ACCESS_TOKEN = $account['access_token'];
}
}
}
$message=$data['facebook_text'];
$attachment = array(
'message' => $data['facebook_text'],
'name' => $data['name'],
'description' => '',
'link'=>$someurl,
'access_token' => $ACCESS_TOKEN
);
if($image_url != NULL) $attachment['picture'] = $image_url;
try {
if($facebook->api('/PAGEID/feed', 'post', $attachment))
{
//other stuff
}
} catch (FacebookApiException $e) {
error_log($e);
//other stuff
}
}
else
{
$login_url = $facebook->getLoginUrl();
header("Location: $login_url");
exit;
}
/* (...) */
?>
Solution can't redirect anywhere, because it's inside form, so all data'll be lost.
I'm not really sure I understand what you want to do here, but this is what I use in a similar situation:
$session = $this->get_admin_session_of_page ($page_id);
$session = unserialize ($session);
$facebook->setSession ($session, false);
In the facebook php SDK there is a method to manually set the session, setSession. I save the page admin user session in DB with serialize, with the offline access and manage pages permission. Then when you need some admin privileges for the application you just unserialize it, and then use setSession. The second parameter is set to FALSE, so that this session is not saved in a cookie and logout the current user.
This way it's not important who is logged in, the work is always done as an admin of the page. I think this is safe to use in an automated script, for example to upload a user photo in a page album.
Of course, you must use caution with this if it gets more involved then that, or implement your own security.