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
}
?>
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 am new to PHP and even newer to SESSIONS
I am working with the Instagram API and I am successfully able to authorize an app, and redirect to a page to display content.
My main folder is called Monkey and it has a sub folder called Instagram.
MY callback url for instagram is success.php located in the instagram folder. When I successfully retrieve an access token from Instagram it redirects to the index file in the Monkey folder.
On my success page, I am creating an array full of data called instaArray. I am trying to pass the array from the success.php in the instagram folder, to the index.php in the monkey folder.
My redirect is simply
header( 'Location: ../index.php' );
Because I am new with sessions, I guess I am doing something wrong. I figured it was straight forward, but I suppose not ha.
On the success.php page, after I build the array I have this
session_start();
$_SESSION['instagram'] = $instaArray;
I thought that should create a session that holds my array InstaArray.
Then, on the index.php page in Monkey, I have this
<?php
session_start();
$get_instagram = $_SESSION['instagram'];
print_r($get_instagram);
?>
But absolutely nothing happens. I've even tried to set the session instagram to a simple numerical value or 1, $_SESSION['instagram'] = 1; and get that on the index page, and it doesn't work either.
Am I doing something horribly, terribly wrong? I've read up on sessions, but because it's new, it's still a little confusing.
Thanks for the help, and I hope I was able to explain everything properly.
EDIT: Here is my success.php page in full
<?php
require 'src/db.php';
require 'src/instagram.class.php';
require 'src/instagram.config.php';
// Receive OAuth code parameter
$code = $_GET['code'];
// Check whether the user has granted access
if (true === isset($code)) {
// Receive OAuth token object
$data = $instagram->getOAuthToken($code);
// Take a look at the API response
$username = $data->user->username;
$fullname = $data->user->full_name;
$id = $data->user->id;
$token = $data->access_token;
$user_id = mysql_query("select instagram_id from users where instagram_id='$id'");
if(mysql_num_rows($user_id) == 0) {
mysql_query("insert into users(instagram_username,instagram_name,instagram_id,instagram_access_token) values('$username','$fullname','$id','$token')");
}
//Set Cookie
$Month = 2592000 + time();
setcookie(instagram, $id, $Month);
// Set user access token
$instagram->setAccessToken($token);
// Retrive Data
$instaData = $instagram->getUserFeed();
// Create Instagram Array
$instaArray = array();
$count = 0;
// For each Instagram Post
foreach ($instaData->data as $post) {
$instaArray[$count]['post_id'] = $post->id;
$instaArray[$count]['name'] = $post->user->username;
$instaArray[$count]['profile_img'] = $post->user->profile-picture;
$instaArray[$count]['img_url'] = $post->images->standard_resolution->url;
$instaArray[$count]['caption'] = $post->caption->text;
$instaArray[$count]['like_count'] = $post->likes->count;
$instaArray[$count]['comment_count'] = $post->comments->count;
$instaArray[$count]['created_time'] = $post->created_time; //Unix Format
$count++;
}
// Start Session For Array
session_start();
$_SESSION['instagram'] = serialize($instaArray);
header( 'Location: ../index.php' ) ;
} else {
// Check whether an error occurred
if (true === isset($_GET['error'])) {
echo 'An error occurred: '.$_GET['error_description'];
}
}
?>
Why not use an ID and then cookies rather than sessions + data (which are usually store on the server in text files in a temporary directory)? And keep all data within a database than allow the client to be accessible to the data. Sessions are also temporary.
Note, do you know if you have "globals" on?!
"Please note when working with sessions that a record of a session is not created until a variable has been registered using the session_register() function or by adding a new key to the $_SESSION superglobal array. This holds true regardless of if a session has been started using the session_start() function."
Reference:
http://www.php.net/manual/en/function.session-register.php
make session_start() first line after php
<?php
session_start();
and remove it from anywhere ele on page.
session_start() should be your first line in index.php also as in success.php
Note: The session_start() function must appear BEFORE the tag:
REF : http://www.w3schools.com/php/php_sessions.asp
I think you need to unserialize() your array in index.php.
$get_instagram = unserialize($_SESSION['instagram']);
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.
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.