I'm totally new to PHP and MySQL but I'm implementing the Facebook PHP SDK in my website. Everything works fine so far but i'm struggling to add the user data to my database (MySQL). Everything I have is a number instead of the username and oauth_uid (I get the number 5 for both fields). This is the code:
<?php
define('db_user','myUserName');
define('db_password','myPassword');
define('db_host','myHost');
define('db_name','myDbName');
// Connect to MySQL
$dbc = #mysql_connect (db_host, db_user, db_password) OR die ('Could not connect to MySQL: ' . mysql_error() );
// Select the correct database
mysql_select_db (db_name) OR die ('Could not select the database: ' . mysql_error() );
require 'lib/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'MYAPPID',
'secret' => 'MYSECRET',
'cookie' => true));
// 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.
$fbuid = $facebook->getUser();
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}else{
header('Location: index.php');
}
$query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook' AND oauth_uid = ". $user['id']);
$result = mysql_fetch_array($query);
if(empty($result)){
$query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username) VALUES ('facebook', {$user['id']}, '{$user['name']}')");
$query = msyql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$paramsout = array('next'=>'http://www.mywebsite.com/test/logout.php');
$logoutUrl = $facebook->getLogoutUrl($paramsout);
}
?>
The above page is called user_page.php and it's where the user is redirected to after the login. I tried to move the "database" code to index.php (where the user does the login) but every effort so far has been unsuccessful. This is the code for index.php:
require 'lib/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'MYAPPID',
'secret' => 'MYSECRET',
'cookie' => true));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$fbuid = $facebook->getUser();
$user_profile = $facebook->api('/me');
header('Location: user_page.php');
} 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'=> 'user_interests,user_activities,user_education_history,user_likes,user_about_me, user_birthday, user_groups, user_hometown, user_work_history, email',
'redirect_uri' => 'http://www.mywebpage.com/test/user_page.php')
);
}
?>
UPDATE* PROBLEM FIXED ( $user_profile instead of just $user) :
$query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook' AND oauth_uid = ". $user_profile['id']);
$result = mysql_fetch_array($query);
if(empty($result)){
$query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username) VALUES ('facebook', {$user_profile['id']}, '{$user_profile['name']}')");
$query = msyql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
}
The Facebook user's data in your code is stored under $user_profile and not $user.
Related
My email id is not stored in database. I want to store details of Facebook user in my database. Actually, I have login page in which, user can also login with Facebook but problem is that i get all details except email. I need store the email id also in database.Please help me.any help is appreciate.
here is my code...
<?php
require 'facebook/facebook.php';
require 'config/fbconfig.php';
require 'config/functions.php';
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
));
$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){
error_log($e);
$user = null;
}
if(!empty($user_profile )){
# User info ok? Let's print it (Here we will be adding the login and registering routines)
$username = $user_profile['name'];
$uid = $user_profile['id'];
echo $email = $user_profile['email'];
$user = new User();
$userdata = $user->checkUser($uid, 'facebook', $username,$email,$twitter_otoken,$twitter_otoken_secret);
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_SESSION['email'] = $email;
$_SESSION['oauth_provider'] = $userdata['oauth_provider'];
header("Location: home.php");
}
}else{
# For testing purposes, if there was an error, let's kill the script
die("There was an error.");
}
}else{
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl(array( 'scope' => 'email'));
header("Location: " . $login_url);
}
It is just a suggestion.
Sometimes If user will not give permission access his email id in Facebook. at that time you will not get email id of that user.
So in that scenario you can store user email as 'userid#facebook.com'.
userid is also unique in facebook for every user. So you will get unique email id for every user.
Replace the below line :
$user_profile = $facebook->api('/me');
with the following code:
$user_profile = $facebook->api('/me?fields=id,name,first_name,last_name,gender,locale,timezone,email');
I am coding an app that uses the Facebook API. In my previous apps, retrieving a user's friend list was easy (some array with all the friends' ids was returned).
With the current API, I cannot found a way to retrieve the very same list. I have read everything that's available on the topic (both S/O and Facebook Dev Docs) but I don't have the final answer: is such a thing still possible.
Here's my code.
<?php
require 'src/facebook.php'; // Include facebook SDK file
//require 'functions.php'; // Include functions
$facebook = new Facebook(array(
'appId' => 'xxxx', // Facebook App ID
'secret' => 'xxxx', // Facebook App Secret
'cookie' => true,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
$user_friends = $facebook->api('/me/friends');
$fbid = $user_profile['id']; // To Get Facebook ID
$fbuname = $user_profile['username']; // To Get Facebook Username
$fbfullname = $user_profile['name']; // To Get Facebook full name
$femail = $user_profile['email']; // To Get Facebook email ID
$friends=implode($user_friends,',');
$link = mysql_connect("localhost", "xxx", "xxx")
or die("Impossible de se connecter : " . mysql_error());
mysql_select_db('mirror',$link);
$sql = "SELECT * FROM users WHERE email = '".$femail."' ";
// on envoie la requête
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
$num_rows = mysql_num_rows($req);
if($num_rows==0){
$sql = "INSERT INTO users (email, name, fbid,friends) VALUES ('".$femail."','".utf8_decode($fbfullname)."','".$fbid."','".$friends."') ";
// on envoie la requête
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
}
if($num_rows!=0){
$sql = "UPDATE users SET fbid = '".$fbid."',friends='".$friends."' ";
// on envoie la requête
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
}
/* ---- Session Variables -----*/
$_SESSION['FBID'] = $fbid;
$_SESSION['USERNAME'] = $fbuname;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;
// checkuser($fbid,$fbuname,$fbfullname,$femail); // To update local DB
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
header("Location: index.php");
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email , user_likes, read_friendlists'
));
header("Location: ".$loginUrl);
}
anything related to friends is either an empty array or an empty var.
I have a big problem about my database e the permission of my application in facebook.
when the user open the app (index.php) and accept the permission, the app go to another page (game.php)... when the game.php is open, the script check in the database to look if the ID of facebook is already present, if not the database make the user.
when the game.php is open at first time, the page generate this error:
OAuthException: An active access token must be used to query information about the current user.
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in game.php on line 67 check1Error: Duplicate entry '0' for key 'UIDfacebook' account
maybe because the ID of facebook is not ready for save in the database, and why? the permission was accept... if I refresh the page, the page will work fine and the database save the ID, username....
INDEX.PHP (REQUEST)
<?php
require('client/facebook.php');
$app_id = '***';
$app_secret = '***';
$canvas_page = "https://apps.facebook.com/***";
$canvas_url = "****";
$code = $_REQUEST['code'];
if(!$code){
$display= 'page';
$scope= 'offline_access, publish_stream, user_about_me, user_likes, email';
$redirect_url = 'game.php';
$oauth_url = 'https://www.facebook.com/dialog/oauth?canvas=1&client_id='.$app_id.'&display='.$display.'&redirect_uri='.urlencode($redirect_url).'&scope='.$scope;
$config = array('appId' => $app_id,'secret' => $app_secret,'cookie' => true,'domain' => true);
$facebook_client = new Facebook($config);
echo "<script type=\"text/javascript\">top.location.href = \"".$oauth_url."\";</script>";
}
?>
GAME.PHP
<?php
require 'client/facebook.php';
require('client/databaselogin.php');
///////////////////
$app_id = "***";
$secret = "***";
$app_url = "https://apps.facebook.com/***/";
//Create our Application instance
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
'cookie' => 'true',
));
// Get User ID
$user = $facebook->getUser();
//Do we have a user?
if(!$user) {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=> $app_url));
//redirect the url to prompt for login and permissions
} else {
try{
//Proced knowing you have a logged in user who's autenticated
$user_profile = $facebook->api('/me');
$name = $user_profile['name'];
$id = $user_profile['id'];
$first_name = $user_profile['first_name'];
$last_name = $user_profile['last_name'];
$link = $user_profile['link'];
$username = $user_profile['username'];
$gender = $user_profile['gender'];
$locale = $user_profile['locale'];
} catch (FacebookApiException $e) {
echo ($e);
$user = null;
}
}
$checkUIDdb = "";
$connection = "wait";
$id = $user_profile['id'];
$username = $user_profile['username'];
$goldDB = "0";
$user_type = "A";
///connect to the database
$connessione = mysql_connect($host, $userdb, $passdb)
or die("error: " . mysql_error());
print ("connect");
echo $connection = "ok";
echo $id;
///
$fb_id = $user_profile['id'];
$locale = $user_profile['locale'];
$con=mysqli_connect($sdb,$userdb,$passdb,$db);
if ($connection == "ok")
{
//Checking User Data # WT-Database
$check1_task = "SELECT * FROM `tabletest` WHERE `UIDfacebook` = " . $fb_id . " LIMIT 0, 30 ";
$check1_res = mysqli_query($con, $check1_task);
$checken2 = mysqli_fetch_array($check1_res);
print $checken2;
//If User does not exist # WT-Database -> insert
if (!($checken2)) {
$add = "INSERT INTO tabletest (id,UIDfacebook, username, goldDB, user_type) VALUES ('', '$fb_id', '$username', '$goldDB', '$user_type')";
mysqli_query($con, $add);
if (!$check1_res) {
echo "check1";
printf("Error: %s\n", mysqli_error($con));
}
}
//Double-check, User won't be able to load app on failure inserting to database
if (!($checken2)) {
//echo "Excuse us " . $first_name . ". Something went terribly wrong! Please try again later!";
}
}
//Close off the MySQL connection to save resources.
?>
<head>
</head>
</body>
</script>
MY APPLICATION
</script>
</body>
</html>
somebody know what is happen?
Thank you very much
EDIT:
I try to use this script for the GAME.PHP:
<?php
require 'client/facebook.php';
$app_id = "aaa";
$secret = "aaa";
$app_url = "http://app.facebook.com/aaa/";
// Create our Application instance
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
));
// Get User ID
$user = $facebook->getUser();
//Do we have a user?
if(!$user) {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=> $app_url));
//redirect the url to prompt for login and permissions
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
} else {
try{
//Proced knowing you have a logged in user who's autenticated
$user_profile = $facebook->api('/me');
$name = $user_profile['name'];
$id = $user_profile['id'];
$first_name = $user_profile['first_name'];
$last_name = $user_profile['last_name'];
$link = $user_profile['link'];
$username = $user_profile['username'];
$gender = $user_profile['gender'];
$locale = $user_profile['locale'];
} catch (FacebookApiException $e) {
echo ($e);
$user = null;
}
}
echo $username;
echo $id;
echo $user_profile;
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>php-sdk example1 </title>
<style>
body {
font-family:Arial, Helvetica, sans-serif;
}
a{
text-decoration:none;
}
but at the first time, the error is similar?
OAuthException: Error validating access token: The session was invalidated explicitly using an API call.
if i refresh the page, the problem disappears....
I have a website where you can login with Facebook. I login to my website, all well and good. But after going on www.facebook.com and log out, when I get back on the website and give refresh, the app works perfectly as if I logged in to Facebook. I tried all sorts of conditions, such as:
$user_profile = $facebook->api('/me');
if($user_profile !== $_SESSION['id']) {
header( 'Location: logout.php' ) ;
}
but nothing works, how can I send it to the logout page if the user is not logged on facebook?
Here is my code:
<?php
// Application Configurations
$app_id = "xxxxxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxx";
$site_url = "xxxxxxxxxxxxxxx";
try {
include_once "src/facebook.php";
}
catch(Exception $e){
error_log($e);
}
// Create our application instance
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true,
));
// Get User ID
$user = $facebook->getUser();
$user_profile = null;
// Get the current access token
// 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.
// print_r($user);
if ($session) {
echo "este";
} else {
echo "nu este";
}
if(!isset($_SESSION['id']))
{
if($user){
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
// Get logout URL
$logoutUrl = $facebook->getLogoutUrl();
try{
//Connecting to the database. You would need to make the required changes in the common.php file
//In the common.php file you would need to add your Hostname, username, password and database name!
mysqlc();
$id = $user_profile['id'];
$name = $user_profile['name'];
$email = $user_profile['email'];
$gender = $user_profile['gender'];
$bio = $user_profile['bio'];
$query = sprintf("SELECT * FROM newmember WHERE id = %s", $id);
$results = mysql_query($query) or die('tubRandom - Query failed: ' . mysql_error() . "<br />\n$sql");
if(mysql_num_rows($results) == 0)
{
$query_two = sprintf("INSERT INTO newmember values(%s,%s,%s,%s,%s,'yes')", $id, $name, $email, $gender, $bio);
$insert_query_two = mysql_query($query_two) or die('tubRandom - Query failed: ' . mysql_error() . "<br />\n$sql");
$_SESSION['id'] = $user_profile['id'];
} else {
$rows = mysql_fetch_array($results);
$_SESSION['id'] = $user_profile['id'];
}
}
catch(FacebookApiException $e){
error_log($e);
$user = NULL;
}
} else {
// Get login URL
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'read_stream, publish_stream, email, user_about_me, user_website, user_work_history, user_relationships, user_religion_politics, user_relationships, user_likes, user_location, user_relationship_details, user_hometown, user_education_history',
'redirect_uri' => $site_url,
));
}
} else {
$user_profile = $facebook->api('/me');
echo $user_profile['name'] . $user_profile . $user_profile['id'] . $_SESSION['id'];
//header( 'Location: logout.php' ) ;
}
?>
Sorry if it is a dummy question, I am a girl. :D
Well, first of all I don't see why you have to make a note of your gender. Anyway, have a look at the FB.getLoginStatus function.
You can check it through $facebook->getUser(); which returns the Facebook User ID of the current user, or 0 if there is no logged-in user... ;) ;) :P
Here is the code of API calls and login through Facebook.
The problem is that when it redirects to Facebook, it does not sign in.
What part of my code is wrong and how can I fix it?
require 'facebook/facebook.php';
require 'config/fbconfig.php';
require 'config/functions.php';
$url = $_REQUEST['lasturl'];
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true
));
$session = $facebook->getSession();
if (!empty($session)) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try {
$uid = $facebook->getUser();
$user = $facebook->api('/me');
} catch (Exception $e) {
}
if (!empty($user)) {
# User info ok? Let's print it (Here we will be adding the login and registering routines)
// echo '<pre>';
//print_r($user);
// echo '</pre><br/>';
$username = $user['name'];
$user = new User();
$userdata = $user->checkUser($uid, 'facebook', $username);
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_SESSION['oauth_provider'] = $userdata['oauth_provider'];
header("Location: ".$url);
}
} else {
# For testing purposes, if there was an error, let's kill the script
die("There was an error.");
}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl();
header("Location: " . $login_url);
}
Actually the code is fine and getting the login credential should work fine. But the problem is here.
if (!empty($user))
I think you should put this first before getting the user info with the API call. If the function getUser returns an ID then you don't need to get the current session just to get the user info.
Try below code : $session = $facebook->getSession(); don't work
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true
));
$uid = $facebook->getUser();
if ($uid) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try {
$user = $facebook->api('/me');
} catch (Exception $e) {
}
if ($uid) {
# User info ok? Let's print it (Here we will be adding the login and registering routines)
// echo '<pre>';
//print_r($user);
// echo '</pre><br/>';
$username = $user['name'];
$user = new User();
$userdata = $user->checkUser($uid, 'facebook', $username);
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_SESSION['oauth_provider'] = $userdata['oauth_provider'];
header("Location: ".$url);
}
} else {
# For testing purposes, if there was an error, let's kill the script
die("There was an error.");
}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl();
header("Location: " . $login_url);
}