I've been searching this site for the answer for a while and I haven't been able to find one for this problem so I'm hoping someone can give me a hand. I'm not exactly an experience PHP programmer so there could be something severely wrong with what I'm doing.
Anyways I am working with another developer who doesn't code in PHP at all and needs access to Facebook information. That being said I'm trying to develop a facebook class which encapsulates all of the Facebook graph calls, allowing for my buddy to call a single function and get all of the information he needs without having to worry about any of the Facebook PHP SDK functions at all. This class I've put in a separate file called CFacebook.php. The code for this class can be found below (I've simply copied the example off of the facebook website)
<?php
require_once 'facebook.php';
class CFacebook
{
//private variables
private $Config = "";
private $FBObject = "";
private $Code = "";
private $Session = "";
private $AppId = '*************';
private $ApiSecret = '*******************';
//I have the API secret and AppID in
//here but for privacy reasons I've taken them out
//constructor
public function CFacebook()
{
$this->FBObject = new Facebook();
$this->FBObject->setApiSecret($this->ApiSecret);
$this->FBObject->setAppId($this->AppId);
}
//Get profile information
public function GetFBProfileInformation()
{
$FBProfile = "";
$ID = $this->FBObject->getUser();
echo "<br />";
if($ID)
{
try {
$FBProfile = $this->FBObject->api('/me','GET');
return $FBProfile;
}catch (FacebookApiException $e)
{
//send back to UI to have user sign in
// 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.
echo "has ID <br />";
$login_url = $this->FBObject->getLoginUrl();
echo 'Please login.';
echo $this->FBObject->getAccessToken()."<br />";
echo $this->FBObject->getApiSecret()."<br />";
error_log($e->getType());
error_log($e->getMessage());
}
}else
{
//return to UI taht user isn't logged in and have user re-sign in
//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.
$Page = "http://fratlabs.com/FacebookTest.php";
$login_url = $this->FBObject->getLoginUrl(array('scope'=>'email,publish_stream,user_likes,user_hometown','redirect_uri'=>$Page));
//$logout_url = $this->FBObject->getLogoutUrl(array('next'=>'http://fratlabs.com/FacebookTest.php'));
echo 'Please login.';
//echo 'Logout Url: Logout';
error_log($e->getType());
error_log($e->getMessage());
}
//echo $this->FBObject->getLogoutUrl(array('next'=>'http://fratlabs.com/FacebookTest.php'));
}
};
?>
This class is included and instantiated in a test page which is where the Facebook login is returned too. Maybe I need to include all of these calls in the same page as the one the facebook login is returned to? The only thing that is confusing me is that once every blue moon the code will work and I will actually create a link to Facebook, but every other time I'm left staring at the login page with the "please login" link on it.
While I am not a php expert myself, I believe it is advised to use try/catch objects for catching exceptions usually as message output not as a logic operator (like if/else) with well-defined pathways of the script like you seem to do. Consider a different approach like initializing the fb session and authenticating the user in the first class and presenting the user information in a second class. But for your partner who only wants fb user info, a message can be delivered in second class if user did not successfully login or authenticate.
For illustration (without functions), I use the code included here.
Related
I am working with both the Facebook PHP SDK and the Facebook JS SDK (using the JS SDK to handle login only, much as is discussed here: https://developers.facebook.com/blog/post/534/).
I have a custom button that I have created and attached to the FB.login() function. My goal is to have the text inside that button say "Log in with Facebook" if the user is not logged in, and to the text inside the button display the user's name if they are logged in.
The problem is that when I try to refer to the $user_profile variable that has the logged in user's information, it works when I use it outside the button, but says that the variable is not set when it is used inside the button (code below). What could be causing this?
<?php
// Get the contents of static-head.html to open the HTML doc:
readfile("static-head.html");
// Include the Facebook PHP SDK so that we can have people login
require_once('fb/facebook.php');
$config = array(
'appId' => 'MY_APP_ID',
'secret' => 'MY_APP_SECRET',
'allowSignedRequest' => false
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
// Get Facebook Login information
if($user_id) {
// 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');
// If this doesn't throw an error, we now we have a $user_profile that we can use
} 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 wait for the user to log in.
error_log($e->getType());
error_log($e->getMessage());
// Set the $user_id to NULL so that there's no confusion elsewhere in the app.
$user_id = NULL;
}
} else {
// Let the user log in through the JavaScript SDK
}
// Just to prove that $user_profile is being recognized:
// ***This works! It returns "Chris"
echo $user_profile['first_name'];
// Function to set the text inside the LogIn/LogOut button:
// ***This doesn't work! It returns "Log in with Facebook"
function getLogInLogOutText(){
if(isset($user_profile)){
return $user_profile['first_name'];
} else{
return 'Log in with Facebook';
}
}
?>
<div id="userLogInLogOut" class="uiControlsDivs">
<button id="userLogInLogOutButton"><?php echo getLogInLogOutText(); ?></button>
</div>
I am utterly confused how this is possible. On one line, the code works and returns the Facebook user's name. Then, just a few lines later, it doesn't work! What is going on?!
Thanks for any help you might be able to provide!
Try parsing the variable to the function, so say make the function:
function getLogInOutText() { ...
into
function getLogInOutText($user_profile) { ...
and call with with that, i.e. :
<?php echo getLogInOutText($user_profile); ?>
Not sure it will work, but it's worth a test. Otherwise try making it a global variable:
PHP reference for variables scope - http://www.php.net/manual/en/language.variables.scope.php
I'm using the FB PHP SDK to log users in. Nothing fancy here - just calling $fb->getLoginUrl() to generate the login link, user goes through to it, authorises, is bounced back to my site and they're logged in. So far, so good.
On a page reserveed for logged-in users I have this code:
echo $fb->getUser(); //supposedly outputs user ID or 0 on failure
But the thing is it outputs the user ID even if I've gone to Facebook manually and logged out of it. It never seems to output 0 for me, i.e. detects that I'm logged out.
What am I missing? Is there a better way to detect login status?
(Note: the JS SDK is not an option for me)
Try using the destroySession method and also kill the session variable when you want to logout.
include('fb-php-sdk/facebook.php');
$config = array();
$config['appId'] = '641xxxx559';
$config['secret'] = '3bxxxxxxcd1c';
$facebook = new Facebook($config);
if(isset($_GET['act']) && $_GET['act'] == "logout") {
$facebook->destroySession();
// destroy session var here. Should be in format of "fmb_$appID"
}
$user = $facebook->getUser();
echo $user;
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;
}
echo "<pre>";
print_r($user_profile);
echo "</pre>";
$logout = $facebook->getLogoutUrl();
//echo $logout;
echo "<a href='test.php?act=logout'>Logout</a>";
} else {
$login = $facebook->getLoginUrl(array("scope"=>"email","display"=>"popup","redirect_uri"=>"http://domain.com/test.php"));
echo "<a href='".$login."'>Login</a>";
}
As you can see I am passing the scope key in the params array to request what I want back. The first time this is run the user will be asked by facebook to confirm what ever is being asked for in the scope.
I'm having some trouble passing a simple variable to Flash from a php file that connects to facebook.
Here's what I do:
When the user comes in to my game, he has the option to login using facebook. If he chooses to do so, I call a php file, that takes him to facebook, where he allows acess to the game and then facebook redirects him to the game.
Once in the game again, I call the same file with a LoadVars, in order to get the user info from facebook. Since the user is already connected to facebook, the variables should be passed to Flash normally, but they simply don't.
If I execute the PHP only, I can see the variable normally, but it simply won't go to Flash.
I did a workaround by redirecting the user to another php file, after allowing access on facebook. This php file would then redirect the user again to the flash game index, and then the variable would be passed normally! The thing is, since I'm redirecting the user to a different url sometimes I get a redirect error... and I didn't wan't to use this method.
Any ideas?
Here's my php code:
<?php
require_once '../facebook.php'; // Require the Facebook PHP SDK
// CONNECT TO THE FACEBOOK APP
$config = array();
$config[appId] = 'xxxx';
$config[secret] = 'xxxx';
$config[fileUpload] = false;
$facebook = new Facebook ($config);
// GET THE USER ID
$user = $facebook->getUser();
if ($user) { // Succesfully got the user id. User is logged in to facebook
$userProfile = $facebook->api('/me'); // Get the basic user info from his profile
$toGame = "";
$toGame .= $userProfile['first_name']."#";
$toGame .= $userProfile['middle_name']."#";
$toGame .= $userProfile['last_name']."#";
$toGame .= $userProfile['birthday']."#";
$toGame .= $userProfile['email']."#";
$toGame .= $userProfile['gender'];
echo $toGame;
}
else { // Failed to get the user's facebook id. Tell him to log on facebook
$params = array ();
$params[scope] = 'publish_stream, user_birthday, email';
//$params[redirect_uri] = 'xxx';
$params[redirect_uri] = 'xxx';
$loginUrl = $facebook->getLoginUrl($params);
echo "needLogin#".$loginUrl; // Tell Flash to redirect the user to the facebook connect page
}
?>
Going over the Facebook API and I'm a bit confused on the right approach. I want users to skip registration, or auto-register them if they sign in with Facebook. So if they sign into Facebook I collect their id, email and create a record in my user table.
If an id exists already in the user table they skip the auto-registration and go directly to the members page. This is my code so far (taken from Facebook's PHP SDK example). When I run the signup script the page shows up as blank, I do not get redirected.
EDIT: seems to be failing right after the require, if I use the following code 'test' never gets printed.
EDIT: I'm using Codeigniter and this script is part of a controller, would that cause a problem with the require?
require 'http://localhost/facebook-php-sdk-6c82b3f/src/facebook.php';
echo "test";
-
public function signup()
{
require 'http://localhost/facebook-php-sdk-6c82b3f/src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
));
// 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
{
$loginUrl = $facebook->getLoginUrl(array('scope' => 'email'));
redirect($loginUrl);
}
print_r($user_profile);
$this->load->model("user_model");
$privileges = 1;
$loginLocation = ip2long($_SERVER['REMOTE_ADDR']);
$active = 1;
$this->user_model->add_user($user_profile->id, $user_profile->name, $user_profile->email, $loginLocation, $privileges, $active);
}
I suggest you read the framework documentation. Adding a library to CodeIgniter is not a hard task. And Facebook library is no exception.
Here's a quick integration I've just come up with:
1.create a config file:application/config/facebook.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['appId'] = 'app_id';
$config['secret'] = 'app_secret';
2.place the sdk files in the libraries folder application/libraries/ and rename the facebook.php file to Facebook.php and replace the php tag with this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
3.in your controller load the config file and then load the Facebook library:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct()
{
parent::__construct();
// Your own constructor code
$CI = & get_instance();
$CI->config->load("facebook",TRUE);
$config = $CI->config->item('facebook');
$this->load->library('facebook', $config);
}
public function index()
{
$user = $this->facebook->getUser();
if($user) {
try {
$user_info = $this->facebook->api('/me');
echo '<pre>'.htmlspecialchars(print_r($user_info, true)).'</pre>';
} catch(FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
} else {
echo "Login using Facebook";
}
}
}
Now in the constructor method, you have just initialized the Facebook library (sdk) and it can be accessed by using: $this->facebook.
Notes:
You can always use an existing library, just google it
A common practice is to extend the core Controller class and add the Facebook library initialization there.
Or create another library, extend the Facebook library, load the config file there and then autoload this new library.
After getting the $user, check session parameters with print_r($_SESSION). After that, check some variables by if(isset($_SESSION['some session var'])). If this condition is true, then navigate to your main page with header("location:main.php"); exit;
You can try using my extension http://github.com/deth4uall/Facebook-Ignited it is set up to work with Facebook. Just update the config file and it will allow you to do what you need to do, as well as some additional methods that I added myself.
do not know why, but it always runs this line:
echo "Login using Facebook";
This is the error message:
couldn't connect to host
But this worked.
I'm having some issues with HybridAuth when I need to redirect "a non-registered user in my local database", to the selected social network: facebook, twitter, windows live, linkedin, openid, etc, more presiously to the "Allow" and "Cancel" page!?
Till now I've got this code going on:
try {
// $via for instance can be: Twitter, Facebook, etc
$hybridauth = new Hybrid_Auth( $myConfig );
$via = ucfirst($via);
$adapter = $hybridauth->authenticate( $via ); // from this line some redirecting accoures
if( $hybridauth->isConnectedWith( $via ) ){
$user = $hybridauth->authenticate($via)->getUserProfile();
}
$profile = Users::model()->findByAttributes(array(
'networkName' => $via,
'networkId' => $user->identifier,
));
if(!is_null($profile)) {
// do a login
} else {
// do a registration + login
}
} catch(Exception $e) {
echo "Error: please try again!";
echo "Original error message: " . $e->getMessage();
die();
}
I hope I've made my point clear. Thanks for all assistance in this matter!
The way I do is to store the provider and the provider identifier in a database, which seems to be the way you implemented as well.
If the user does not exist, I create it and then redirect the user to the user profile editor. Otherwise I just redirect to the main page or dashboard.
The provider data has all the required fields for creating a basic profile. If you need something else, redirect the user to a page with a form for him to complete the registration. Store anything else you need in SESSION or similar. You can use $hybridauth->restoreSessionData($_SESSION['HYBRID']) to keep the session on.