I am developing a facebook app using PHP.
I am able to login using the below code
<?php
$app_id = "XXXXXXXXXXXXXXXXX";
$canvas_page = "http://apps.facebook.com/sandysfirst/";
$auth_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" .urlencode($canvas_page)."&scope="."publish_stream,read_stream,offline_access";
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
}?>
<?php
include_once "src/facebook.php";
$app_id = 'XXXXXXXXXXXXXXXXXXX';
$application_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$facebook = new Facebook(array(
'appId' => $app_id,
'fileUpload' =>true,
'secret' => $application_secret,
'cookie' => true, // enable optional cookie support
));
if ($facebook->getSession()) {
$user = $facebook->getUser();
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
echo "<br/><br/><br/><br/> Welcome ".$fbme['name'];
}
echo "<html>
and the HTML follows below that with a form action.
I want to know how I can get the same user id or session on the second page once the form is submitted.
I am not using facebook.php of sdk 3.0.
I don't know the facebook api, but from some basic php there's a few methods you could use:
1 - Add the uid as a hidden field in the form.
<input type="hidden" name="uid" value="$uid">
2 - Add it to the action url
<form action="submit.php?uid=$uid">
However the better way is to use the facebook api, pretty much the same way you've got it listed there already (from the include_once "src/facebook.php";), to retrieve the uid each time, otherwise you leave it open to security hacks (easy to pass a fake uid in a form).
Related
This question already exists:
Facebook getUser() always returns 0 [duplicate]
Closed 10 years ago.
This Facebook PHP SDK is driving me CRAZY!
getUser() always return 0
let me explain what I do:
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
));
$user = $facebook->getUser();
if ($user === 0)
{
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email, publish_stream',
'redirect_uri' => FB_REDIRECT_URI
));
echo "<script type='text/javascript'>window.location = '$loginUrl';</script>";
exit();
}
simple code, equals to the example. Good...
I have this code in login.php and complete.php
I send the request from login.php and set the redirect_uri to complete.php (the same I wrote in Website with Facebook Login...obviously a complete URL like https://www.example.com/complete.php)
I really do not understand Why I still get 0!
It is not possible, Im logged in Facebook following the LoginURL.
I also passed the "permissions" with the URL.
I already registered at this app, so I really do not understand the reason why this SDK is continuing to return 0.
Could someone help me?
INFO:
I only have selected Website with Facebook Login, nothing else... "App on Facebook" is not selected.
EDIT:
https://www.facebook.com/login.php?api_key=216182291818102&skip_api_login=1&display=page&cancel_url=https%3A%2F%2Fwww.example.com%2Fusers%2Fcomplete%2F%3Ferror_reason%3Duser_denied%26error%3Daccess_denied%26error_description%3DThe%2Buser%2Bdenied%2Byour%2Brequest.%26state%3D720fab495a21639032816d3c688ae87b&fbconnect=1&next=https%3A%2F%2Fwww.facebook.com%2Fdialog%2Fpermissions.request%3F_path%3Dpermissions.request%26app_id%3D216182291818102%26redirect_uri%3Dhttps%253A%252F%252Fwww.example.com%252Fusers%252Fcomplete%252F%26display%3Dpage%26response_type%3Dcode%26state%3D720fab495a21639032816d3c688ae87b%26perms%3Duser_birthday%252Cemail%26fbconnect%3D1%26from_login%3D1%26client_id%3D216182291818102&rcount=1
i am used same example and it's work for me.
my connection is like this,try to add cookie = true and check, hope will work for you
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true,
));
Where did you get the example from? This is from the FB Developer page (https://developers.facebook.com/docs/authentication/server-side/):
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_URL";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
else {
echo("The state does not match. You may be a victim of CSRF.");
}
?>
Your code is looking good. You should provide one more parameter to facebook array that is cookie=>true. You should refer the following tutorial which worked for me.
http://www.9lessons.info/2011/02/login-with-facebook-and-twitter.html
Hope it will work for you.
Now I am posting the configuration of APP.
App ID/API Key
xxxxxxxxxxxxxxxxxx // your App ID
App Secret
xxxxxxxxxxxxxxxxxxxxxxx //Your secret key
Site URL
http://localhost/ //your site url
Contact Email
example#example.com //your email id
Support URL
http://localhost //your support url
I only provided this much information and its perfectly working for me.
Try this
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true,
));
and first you login in facebook account then execute this code.
$user=$facebook->getUser();
I am developing my first facebook app, which includes creating a new album and posting photos to the user wall. By learning through facebook documentation and few tutorial and came up this code, but I am getting following error with it.
Fatal error: Uncaught OAuthException: Error validating application. Thrown in /home/base_facebook.php on line 1106
Plus: I don’t know if it matters or not, but when I am printing out the
echo $facebook->getUser();
variable it giving me ‘0’ in return even though user (which in this case is myself) is logged in.
Kindly help me through this.
Code:
$config = array(
'appId' => '3663250024856',
'secret' => 'b14ac6d2b7dbdtyb259599b06983e881',
'fileUpload' => true,
'cookie' => true
);
$facebook = new Facebook($config);
echo "USER STATUS:".$facebook->getUser();
$facebook -> setFileUploadSupport(true);
$album_details = array('message' => 'Album desc', 'name' => 'Album name');
$create_album = $facebook -> api('/me/albums', 'post', $album_details);
$album_uid = $create_album['id'];
$photo_details = array('message' => 'Photo message');
$file = "temp/".$imageName;
$photo_details['image'] = '#' . realpath($file);
$upload_photo = $facebook -> api('/' . $album_uid . '/photos', 'post', $photo_details);
The best working solution I've found in the web. Add the below code at the top of your php page:
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_URL";
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
}
Even though the user is logged in, the user needs to give permission to your app before you can make api calls.
Basically the flow for user authentication using facebook php sdk should be like this:
Detect whether the user is logged in and given permission to your app.
If he hasn't given permission, redirect him to the login and application permission page. After logging in and giving permission, he'll be redirected back again to your application page.
Otherwise, show the content of your app, make api calls,...
Here is a modified sample code from the php sdk's documentation page to handle authentication that should work if you just modify the appId, appSecret and redirect_uri:
<?php
require_once 'fb_php_sdk/facebook.php';
$appId = 'your_app_id';
$appSecret = 'your_app_secret';
// Create your Application instance (replace this with your appId and secret).
$facebook = new Facebook(
array(
'appId' => $appId,
'secret' => $appSecret,
'fileUpload' => true,
'cookie' => true
));
// Get User ID
$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;
}
}
// Login or logout url will be needed depending on current user state.
if ($user)
{
$logoutUrl = $facebook->getLogoutUrl();
}
else
{
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => '',//these are the extended permissions you will need for your app, add/remove according to your requirement
'redirect_uri' => 'http://apps.facebook.com/test_app_azk/',//this is the redirect uri where user will be redirected after allow,
));
}
if ($user)
{
//show the content of your app
//make api calls
var_dump($user_profile);
}
else
{
//redirect user to loginUrl
echo "<script>parent.location = '".$loginUrl."';</script>";
}
Hope this helps.
The problem might lie within the else statement. Instead of using else use if(!user). That should fix the issue.
I just need simple and working facebook app. I bought ssl for this and i dont want too much expenses.
If user allowed app it will write his name and gender and his/her friends gender.
my app doesnt redirect after user allow the app. I cant fix it so just need basic app with out url redirecting.
ı used this code but it doesnt work. it need to be corrected:
require_once("facebook.php");
$facebook = new Facebook(array(
'appId' => '***',
'secret' => '***',
'scope' => 'manage_pages,offline_access,publish_stream,user_photos'
));
$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) {
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
Here is the simple one page application full fills your needs
make the file with name index.php
download the facebook library download here
<?php
require_once 'library/facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'appid',
'secret' => 'secret',
'cookie' => true,
));
$app_id = 'appid';
$canvas_page = "canvas_page_link";
$auth_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page) . ("&scope=email,read_stream&response_type=token");
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
//getting the userid and some other data for verification
//get the user id
$UserId = $data["user_id"];
echo 'UserId;' . $UserId;
//get the user access token
$token = $facebook->getAccessToken();
echo "</br>" . 'Access_Token:' . $token;
//set default access token and profile
$facebook->setAccessToken($token);
$user_profile = $facebook->api('/me');
//get the user name
$user_id = $facebook->getUser();
$user_profile = $facebook->api('/me','GET');
$user_name = $user_profile['name'];
echo "Name: " . $user_name;
$user_gender = $user_profile['gender'];
echo "Gender: " . $user_gender;
}
?>
I have a facebook iframe app which correctly logs in and authorizes the app, but getUser() only works on the first page. As soon as a user clicks a link to a new page within the iframe, getUser() returns 0.
What's strange is that this same code works for another app... I do all the clicking I want and getUser() returns a valid ID.
The app that doesn't work: https://apps.facebook.com/celestial_glory/
The one that does (same codebase): https://apps.facebook.com/uprisingstlouis/
Here's the code I am using:
require_once ('fb/facebook.php');
// snip... set $app_id, $secret, and $canvas_page
// first, try normal facebook getUser(). If that works, awesome.
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
));
$signed_request = $_REQUEST['signed_request'];
// Get User ID
$user = $facebook->getUser();
if ($user != '0') return 'fb=' . $user; // works once
// getUser() didn't work. Try oAuth. Maybe user needs to log in or
// authorize the game?
$auth_url = 'http://www.facebook.com/dialog/oauth?client_id='
. $app_id . '&redirect_uri=' . urlencode($canvas_page);
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo '<a target="_top" href="' . $auth_url . '">Login to Facebook</a>';
exit;
// normally we would auto-redirect, but with a uid of 0, this just auto-redirects
// echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
return 'fb=' . $data['user_id'];
}
any ideas? I have triple-checked app ids and secrets and canvas pages. If those were wrong, I expect no page, not even the first, would work.
Change Facebook PHP-SDK initialization to:
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
'cookie' => true // this!
));
getUser works on the first page because it can get the user from signed_request (POST'ed by Facebook to your canvas page URL). Thus you need some way to track your user once he starts navigation deeper within your application. You could pass signed_request somehow all by yourself or simply enable built-in PHP-SDK cookie support as suggested above.
I got given a code from a friend that displayed the app users birth date on the app canvas.
I have tried to change it in order to echo the users own ID. It works for myself (the creator) and it also works for a friend that i have designated as a developer. But for anyone else it brings up this error:
Warning: file_get_contents(https://graph.facebook.com/me?
fields=id&access_token=228073413942115|460d2e1ffd0b4cc6b5cb480d53f60d6e)
[function.file-get-contents]: failed to open stream: HTTP request failed!
HTTP/1.0 400 Bad Request in /home/robsdmr/public_html/fb/index.php on line 34
The code is as follows.
<?php
require_once("src/facebook.php");
$app_id = "xxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
$canvas_page = "https://apps.facebook.com/roblewtest/" .$app_id;
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true,
));
$access_token = $facebook->getAccessToken();
$auth_url = "https://www.facebook.com/dialog/oauth?scope=user_id&client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page);
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
}
$graph_url = "https://graph.facebook.com/me?fields=id&access_token=" . $access_token;
$result = json_decode(file_get_contents($graph_url));
echo "{$result->id}"
?>
I am pretty new to this so pointers would be great
I have a feeling that it is the scopes that i am not quite to grips with, but i really need this working.
Thanks a lot guys n gals.
R.
Try using SDK's graph methtod:
$result = $facebook->api('/me?fields=id');
And also to get login url you could use:
$auth_url = $facebook->getLoginUrl();
Documentation:api(), getLoginUrl()
Also simplified you code, see here.