I've been going through FB docs but I think I am totally lost now. My task is quite simple: I need to have an "import" link, user clicks it and receives FB popup where he authorizes the site, user is redirected back to my site, I access user's FB profile and retrieve some data. Also: I need to access and retrieve profile in PHP.
The first part goes well. I created mysite.com?page=import link which opens in popup and then redirects to https://graph.facebook.com/oauth/authorize?...
User then allows access and the popup is redirected back to mysite.com?...#access_token=...&expires_in=4031
Then I am going to close the popup and instead refresh the parent window that opened this popup by redirecting it to something like this mysite.com?page=register&access_token=...&expires_in=4031
Then I was going to use their PHP SDK hoping that it can take this access token and allow me to get user's data. However I have no luck so far. I've tried lots of things and went through facebook.php but can't see a solution. Please let me know how to do this: authorize user in a popup and then gather the profile data in php.
here is your working example.
it has a redirect and works entirely in php, i didnt do javascript beacuse this is easier and faster to write.
the main difference is that the returned code after the authorization page is only a code which allows you to fetch the actual access token incombination with your client secret.
otherwise anyone could get an access token for yuor application or you would have to pass your secret token in the url.
thats the reason for the second step.
in javascript we dont need that because facebook only redirects back to a whitelisted domain
and as the access token is in the url fragment after the # tag the server cant access it, only the client. and this is ensured to be yours erver as your domain must be whitelisted.
but it needs more client interaction...
well anyway. you can use the code i wrote for yuo and you can also do it in a popup. you just have to pass your variables to the form or whatever you are doing but this shouldnt be a problem. i did it this way because you said you needed it in php. a good javascript example can be found on the facebook connect page here: http://developers.facebook.com/docs/guides/web#login
any questions? comment!
ps: i put the # sign before the file_get_contents function because you might geht ssl errors, you should actually use curl for that and do error handling!
save this file as whatever.php to your server, check the 4 config variables in the top and hit it
<?
// your app id
$app_id = "123";
// your secret token
$mysecret = '***';
// your website correctly set up in facebook app config
$redirecturl = "http://www.yourdomain.com/whatever/thisfile.php?action=authorized";
// what you want to fetch
$scopes = array('email','user_interests'); // whatever you want
if($_GET['action'] == 'authorize') {
$url = "https://graph.facebook.com/oauth/authorize?client_id=".$app_id."&redirect_uri=";
$url .= urlencode($redirecturl);
$url .= "&display=popup";
$url .= "&scope=".implode(',',$scopes);
header("Location: $url");
exit();
} else if($_GET['action'] == 'authorized') {
$code = $_GET['code'];
$tokenurl = 'https://graph.facebook.com/oauth/access_token'.
'?client_id='.$app_id .
'&redirect_uri='.urlencode($redirecturl).
'&client_secret='.$mysecret.
'&code='.$code;
$token = #file_get_contents($tokenurl);
$token = preg_match('/access_token=(.*)&/',$token,$extracted_token);
$token = $extracted_token[1];
$dataurl = 'https://graph.facebook.com/me?access_token='.$token;
$result = #file_get_contents($dataurl);
$data = json_decode($result);
echo "<pre>".print_r($data,true)."</pre>";
} else {
?>click here to immport your data<?
}
?>
Related
I built a php website where a user signs in and a session with the user credentials are created. For every page that requires users to be signed in, I created a function where it checks for the session variables. Now all of my code seems to work like a charm when I use the site directly with the server IP address (example: http://123.45.67.891/mywebsite). However, once I assigned a subdomain via "domain masking" from GoDaddy, all the session seems to not work at all. I tried to search through other Stackoverflow posts and any google searches but cannot seem to resolve it. The website does not redirect any pages to a different subdomain like I've read to other posts. All redirects on this website I built is within the same subdomain masking. Now, I do suspect that this masking is causing the cookies to get confused...
So the result I'm getting currently is that when you submit the signin form, the php code runs, creates the sessions successfully, returns success info to ajax, the ajax success function redirects to the next page, but as soon as it reaches to the next page, my code to check for credentials immediately throws the user back to the index page as it does not see any Sessions. The function is working as intended as I wrote it to prevent anyone from accessing the page without being signed in. But with the domain masking, a user is never able to signin...
Is there a solution to this or do I need to rid the subdomain masking and purchase a separate domain for this so it can work like a normal website?
Below is a snippet where I create the session and the snippet where I run the credential check.
Thanks!
//====== Create sessions at signin
... mysqli calls before this with Posts from ajax ...
session_set_cookie_params(0,'/','.mywebsite.com');
session_start();
$_SESSION["TYPE"] = $row[3];
$_SESSION["USERNAME"] = $row[0];
$_SESSION["FULLNAME"] = $row[2];
session_write_close();
... some codes returning success call to ajax where javascript then redirects to the user dashboard page...
//======= Credential Check
function checksignin(){
session_set_cookie_params(0,'/','.mywebsite.com');
session_start();
if(!isset($_SESSION["USERNAME"])){
session_destroy();
header('Location: ../index.php');
exit;
else if(empty($_SESSION["USERNAME"])){
session_destroy();
header('Location: ../index.php');
exit;
}
}
I have created a facebook login using the tutorial from http://www.9lessons.info/2011/02/login-with-facebook-and-twitter.html. But the problem is after logging in the user will be redirected to the index.php page. How can i redirect him to the page from which he has clicked the login.
I tried saving the previous url to session. But i don't know why, its not working. It worked for normal login, but not for facebook. I also tried saving the previous url to cookie. It also didn't work. Url is saving, But after logging in session url/cookie url is lost. Can someone pls tell me an alternative method???
Example to store the current page
Do on all but your login page before redirect:
session_start();
$_SESSION['lastpage'] = $_SERVER['HTTP_REFERER'];
On all other pages :
session_start();
if(isset($_SESSION['lastpage'])) {
$lastpage = $_SESSION['lastpage'];
$_SESSION['lastpage'] = false;
unset($_SESSION['lastpage']);
header("location: " . $lastpage);
}
Something like that should work. Make sure to santize the $_SESSION variable, and also validate the last URL was from your site (or supported site) before setting the session var.
A user is logged in to my website and I have all the details I need to retrieve information on their account. I know how to retrieve the users profile image url, but I am not sure if this is a 'static' link. If it is not a static link, I have to fetch the URL each time which seams like a bad idea. I would really be hammering google with all my requests. (I'm not worried about googles servers, I am more worried about my api quota.)
So is there a way to get a static link to a users profile image. If not, what is the best option?
The developer policies at https://developers.google.com/+/policies state, in section B1c:
Don’t use stale data. You can cache or store data you’ve obtained through the Google+ API, but to the extent reasonably possible within the context of your application, use fresh data recently fetched from the API. If the fresh data reveals that content is gone (for instance, because a user deleted it), delete it and don’t use your stale copy. For clarity, if you comply with these requirements, you may cache data longer than specified by the cache header.
The guideline is vague, clearly, but it does say that you shouldn't need to re-fetch the profile info/photo every time... but you should re-fetch it periodically and store it, at least during a session.
Since you're talking photo, consider that people may change their photo somewhat frequently. I would say that it makes sense to cache the image during a user session, but might be reasonable to refresh it when they sign in for a new session.
I'm using this to get users info (and image info, and save that to db for later usage)
$google_client_id = "MY GOOGLE CLIENT ID";
$google_client_secret = "MY GOOGLE CLIENT SECRET";
$redirect_URL = "http://url.to.redirect";
$gClient = new Google_Client ();
$gClient->setApprovalPrompt ("auto");
$gClient->setApplicationName ("My Application Name");
$gClient->setClientId ($google_client_id);
$gClient->setClientSecret ($google_client_secret);
$gClient->setRedirectUri ($redirect_URL);
$google_oauthV2 = new Google_Oauth2Service ($gClient);
//If user wish to log out, we just unset Session variable
if (isset ($_REQUEST["reset"]))
{
unset ($_SESSION["google"]["token"]);
$gClient->revokeToken ();
header ("Location: ".filter_var ($redirect_URL, FILTER_SANITIZE_URL));
}
if (isset ($_GET["code"]))
{
$gClient->authenticate ($_GET["code"]);
$_SESSION["google"]["token"] = $gClient->getAccessToken ();
header ("Location: ".filter_var ($redirect_URL, FILTER_SANITIZE_URL));
return;
}
if (isset ($_SESSION["google"]["token"]))
{
$gClient->setAccessToken ($_SESSION["google"]["token"]);
}
if ($gClient->getAccessToken ())
{
//Get user details if user is logged in
$google_data = $google_oauthV2->userinfo->get ();
$google_user = array (
"id" => $google_data["id"],
"email" => filter_var ($google_data["email"], FILTER_SANITIZE_EMAIL),
"profil_url" => filter_var ($google_data["link"], FILTER_VALIDATE_URL),
"picture" => filter_var ($google_data["picture"], FILTER_VALIDATE_URL)."?sz=200"
);
$_SESSION["google"]["token"] = $gClient->getAccessToken ();
// we have users data now so we do with it what we want... save to db?
}
else
{
//get google login url and redirect user to it
$login_url = $gClient->createAuthUrl ();
header ("Location: $login_url");
exit;
}
I read many question and post about my question but all were not helpful.
I develop website, and in login page i use session.
As i know session is end when browser close,, but my session is not end on browser close..
I want to access my web with out login
here is code that create session
$_SESSION['session_name'] = 'session value';
$_SESSION['is_admin'] = '1';
$general->redirect('home.php');
by this code session is created and i access website definitely,
i try to add session manually , and set these session name in manually session, and then i want to access website,..
you Not give me full detail, but please give me initialize suggestion and helpful source where i read about this.
Thank you.
Simply create a separate page on your website’s root (preferably protected by a HTACCESS password). Call it something like *hack_login.php* (or something more cryptic).
<?php
session_start();
$_SESSION['session_name'] = 'session value';
$_SESSION['is_admin'] = '1';
?>
Now when you access that page, and provided your session cookie is written correctly, you should be authorized when you access your website through the front page.
Don't forget to remove that page once your tests are done ;)
Is there a way to use the facebook connect api in a static way?
When we use the facebook php sdk the link or button to login to facebook is something like https://www.facebook.com/dialog/oauth..................
what I want is to eliminate the include of the php sdk on every page, because it will cause some extra processing and server load in peak times.
I want to make a session check to know if the user is logged in, by checking for exemple if his facebook user id and name are stored in the session, then if not, display a static login button. then after login with facebook he gets to facebook-login.php which will include the facebook php sdk and process his data and store them in the session, so that he remains logged without including the php sdk in each page.
the url structure that I get with $facebook->getLoginUrl() is:
https://www.facebook.com/dialog/oauth?client_id={MY_APP_KEY}&scope={PERMISSIONS}&redirect_uri={MY_SITE/facebook-login.php}&state={A_32_CHAR_CODE_LIKE_MD5_MAYBE}
The final question is: WHAT WOULD BE THE URL IN THE LOGIN BUTTON?
just load the sdk and do something like:
echo 'Connect to Facebook';
that url will always be valid for a logged out user
This is a good question. First, a user is logged into you app means that you have a valid access token for the user.
And there is no way to be sure that an access token is valid before making an API call with this access token. So if you want to make sure the user is still logged in on each page, you have to make an API call to Facebook on each of them. Kind of heavy, but there is no other solution.
What you can do is assume that the access token you have is valid and check only once a while (when you really need to be sure the user is logged in).
You can have different scenario :
you have no Facebook data about the user : the user is not logged in your app for sure.
you can read the user ID, but you may not have an access token for this user : the user may not be logged in.
you can read an access token, but it may not be valid (has expires or revoked by the user) : the user may not be logged in.
you have a valid access token : the user is logged in for sure.
You can read the user ID and the access token in the session. The session array looks like that :
[fb_148195765253871_access_token] => 14819576525...
[fb_148195765253871_user_id] => 1536397056
The number in the keys of the array (here 148195765253871) is your app ID.
So what you can do on each page is to check if those keys are set and if they are not, load the SDK and double-check (because the access can be store in some other places that the SDK is reading) :
if (isset($_SESSION['fb' . YOUR_APP_ID . 'access_token'])) {
// assume to user is logged in
// and keep going
} else {
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
// Make an API call to be sure the user is logged in
// ie : that you have a valid access token
$user = $facebook->getUser(); // User ID
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
if ($user) {
// The user is logged in for sure
} else {
// The user is not logged in for sure
// Make him log in
echo 'Login with Facebook';
}
}
Hope that helps !
The selected answer does not really answer the question.
If you would like to isolate all the Facebook code necessary for generating the getLoginUrl function call into a separate file you can do this easily by using meta refresh.
So in your header point the link "Login With Facebook" to "facebook_login.php". On this page include the necessary calls from the SDK for getLoginUrl and than add the following line of HTML.
<meta http-equiv="refresh" content="0;URL=<?=$helper->getLoginUrl(array('email', 'user_friends'));?>">
I tested this out multiple times and it works.
FYI using Facebook SDK 4.0.