Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if user is logged in with new facebook php api

I am migrating my old FB app to the new graph API using the PHP API

I have two pages: public ones (which require no user login) and private ones (which do)

So the code of every single php page in my application works as follows:

if (this_page_requires_user_login){
      $facebook = new Facebook(...) ;
      $session = $facebook->getSession ;
      if (!$session){
              $url =$facebook.getLoginUrl(array(next => current_page );
              echo "<fb:redirect url=$url/>" ;

}
// the rest of the code continues here

Now as you can see, this way of working forwards every single page to the login url and while it works, it is also slow and appends the &session={bla} string to very single url.

I need a way to check where a user is already logged in before I redirect him to loginpage. But i can not find such method in the php api. What's the best way to do this?

EDIT

This seemed to do the trick

if ($session) {
  try {
    $me = $facebook->api('/me');
    if ($me) {
       // here comes your code for user who is logged in
    }
  } catch (FacebookApiException $e) {
    login()
  }
}else{
 login()
}

function login(){

  $url =$facebook.getLoginUrl(array(next => current_page );


      echo "<fb:redirect url=$url/>" ;
}
like image 504
Hendrik Avatar asked Jul 14 '10 09:07

Hendrik


People also ask

What is Facebook_ client_ token?

An access token is an opaque string that identifies a user, app, or Page and can be used by the app to make graph API calls. When someone connects with an app using Facebook Login and approves the request for permissions, the app obtains an access token that provides temporary, secure access to Facebook APIs.


1 Answers

If I am reading your code correctly, only if no session is returned do you do the redirect? According to comments in Facebook's example, even if you get a session back, you can't assume it's still valid. Only trying an API call that requires a logged in user will you know for sure. This is the best way I've seen to reliably determine login/logout status.

if ($session) {
  try {
    $me = $facebook->api('/me');
    if ($me) {
      //User is logged in
    }
  } catch (FacebookApiException $e) {
    //User is not logged in
  }
}
like image 193
jhchen Avatar answered Sep 30 '22 14:09

jhchen