简体   繁体   中英

Facebook api php-sdk

I started playing around with the fb api a couple of days ago. I am using the fb php-sdk to authenticate users with facebook on my site. I use the following piece of code which works, but intermittently and I cant seem to figure out why.

    <?php
    session_start();


    require './library/facebook.php';
    include './library/fb_keys.php';

    // Create app instance
    $facebook = new Facebook(array(
   'appId'  => YOUR_APP_ID,
   'secret' => YOUR_APP_SECRET,
    ));

   // Get User ID
   $user = $facebook->getUser();

   //Check Access token

   if ($user) {
   try {
   // Proceed with logged in user.
   $user_profile = $facebook->api('/me');
   } catch (FacebookApiException $e) {
   //error_log($e);
   $user = null;
    }
   }

 // Login or logout based on user state
 if ($user) {
 $logoutUrl = $facebook->getLogoutUrl();

   } else {
  $loginUrl = $facebook->getLoginUrl(array('scope' => 'status_update, publish_stream', 'redirect_uri' => 'http://webaddress.com/web/'));

    }

    ?>

This is really straightforward piece of code that I got from the https://github.com/facebook/php-sdk/ .

I usually can't log in when I clear all my cookies and/or session is cleared. but once I log on to the facebook.com site all seems to work again. So it indicates that I am missing something with regard to setting the session or cookies.

Any help will be appreciated.

I guess by not working you mean that user isn't redirected to the login page?

You do get the loginUrl but you're not redirecting user there.

This can be easly done with adding the following code after $loginUrl line:

print '<script language="javascript" type="text/javascript"> top.location.href="'. $loginUrl .'"; </script>';

If I'm wrong please tell me exactly what you mean under "can't log in", what stops you etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM