I have, on my website, a login with Facebook (API PHP). When the user, click on the "Connect with Facebook" (and all it's ok), I give him a session to log in him on my website ...
But, if the user close his browser, the session is destroy ...
So, my question is, how to do, to do a persistent connection ...
Here is my code:
if(!$member->isLoggedIn()){
//set Facebook
$fb_s = Zend_Registry::get('config');
$config = array(
'appId' => $fb_s->FACEBOOK->appId,
'secret' => $fb_s->FACEBOOK->secret
);
$facebook = new Facebook($config);
$user = $facebook->getUser();
//not logged in on website, but logged in on FB
if($request->getControllerName() != "login"){
=========> $user is empty ....
if($user){
try{
$user_profile = $facebook->api('/me');
$membres = new Membre();
if(!$membre = $membres->getMemberByFB($user_profile['id'])){
// Need to be re logged in";
if($a = App_Frontend_Login::LogMeFB($membre) == 1){
$this->_redirect('/');
}
}
}catch(FacebookApiException $e){
error_log($e);
$user = null;
}
}
}
Thank you for your help (in advance) ...
If you want to login a user when the php session is over but is logged on facebook, you must use javascript facebook api to check user state in client side.
That's the way for 'remember me' option if you don't want to force user to click in 'connect with facebook' if your app has been already authorized.
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');
?>
I have a problem with my logging into my Facebook application.
When I click "login" I get redirected to Facebook to accept the permissions then Facebook redirects me back. But it doesn't change anything. The URL down is dynamic generated. When I try the same script on an other URL that's not dynamic it's work.
Here is the URL there i try to perform a login.
http://www.testaiq.se/test_592.html
What could be the problem? PHP is behind the URL over here.
require_once("facebook/facebook.php");
// Creating our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'XXX',
'secret' => 'XXX',
));
// Getting User ID
$user = $facebook->getUser();
// Get Access token
$access_token = $facebook->getAccessToken();
// 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.
// Retrieving user's friend list using fb graph api
$user_profile = $facebook->api('/me','GET');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'user_likes'
));
}
I have created a facebook app which I'm using as a Page Tab. I'm using the PHP SDK and Javascript SDK, and have authenticated and set it up perfectly to display the dialogs and then my page within the tab iframe.
I would now like to load other pages of my site asynchronously, however I can not access the users data (name, etc.) on the asynchronously loaded pages. How do I pass the authentication and variables to the ajax loaded pages?
(EDIT) Solution:
The PHP SDK creates a session automatically to use amongst pages loaded with ajax (or anywhere). You just have to call your authentication routine on each page loaded with ajax in order to access the data (using a php include is best).
I load pages into a div using a simple jquery load:
$('div#page').load('your-page.php');
And this is the routine I run on each php page:
<?php
//facebook application configuration
$fbconfig['appid' ] = "YOUR APP ID";
$fbconfig['secret'] = "YOUR APP SECRET";
$fbconfig['baseUrl'] = "SOURCE FILES BASE URL";
$fbconfig['appBaseUrl'] = "APP BASE URL";
/*
* If user first time authenticated the application facebook
* redirects user to baseUrl, so I checked if any code passed
* then redirect him to the application url
*/
if (isset($_GET['code'])){
header("Location: " . $fbconfig['appBaseUrl']);
exit;
}
//
if (isset($_GET['request_ids'])){
//user comes from invitation
//track them if you need
}
$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.
$user_profile = $facebook->api('/me');
} 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
$userInfo = $facebook->api("/$user");
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
?>
It depends of how you do your request, but you can save the data in a $_SESSION variable, like $_SESSION['userData'] = $facebook->api('/me'); and call it on every pages.
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.
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.