如何检查用户是否使用新的 facebook php api 登录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3244912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:07:23  来源:igfitidea点击:

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

phpfacebookfacebook-graph-apifacebook-login

提问by Hendrik

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

我正在使用PHP API将我的旧 FB 应用程序迁移到新的图形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:

因此,我的应用程序中每个 php 页面的代码都按如下方式工作:

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.

现在正如您所看到的,这种工作方式将每个页面都转发到登录 url,虽然它有效,但它也很慢,并将 &session={bla} 字符串附加到非常单一的 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?

在将用户重定向到登录页面之前,我需要一种方法来检查用户已经登录的位置。但是我在 php api 中找不到这样的方法。做到这一点的最佳方法是什么?

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/>" ;
}

回答by jhchen

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.

如果我正确阅读您的代码,只有当没有返回会话时,您才进行重定向吗?根据Facebook 示例中的评论,即使您恢复了会话,也不能假设它仍然有效。只有尝试需要登录用户的 API 调用才能确定。这是我见过的可靠确定登录/注销状态的最佳方式。

if ($session) {
  try {
    $me = $facebook->api('/me');
    if ($me) {
      //User is logged in
    }
  } catch (FacebookApiException $e) {
    //User is not logged in
  }
}