Get Facebook user profile data in php

2019-06-14 01:21发布

问题:

The following code should return the email address of the user logged in.

  <?php


     require_once('facebook-php-sdk/src/facebook.php');
    // Create our Application instance (replace this with your appId and secret).
    $facebook= new Facebook(array(
      'appId' => '2453463636',
          'secret' => '365653656565656',
          'allowSignedRequest' => false,
    ));


    $user = $facebook->getUser();
    print_r($user);
    if ($user) {
      try {
        // Get the user profile data you have permission to view
       // $user_profile = $facebook->api('/me');
        $user_profile = $facebook->api('/me?fields=picture.width(100).height(100),first_name,last_name,username,email');
        echo $user_profile['email'];

      } catch (FacebookApiException $e) {
        $user = null;
 error_log($e);
     print_r($e);
      }
    } else {
     die("failed");
    }

    ?>

Instead it returns "failed", and print_r($user) returns 0.

Really don't know what to do.

In the dashboard:

I have set up a website platform to view my app.

The jist: The "App Domains" = www.app.com

"Site Url" = http://www.app.com/test

The site url is actual the app. I try to access the getUser in urls such as http://www.app.com/test/fbuser, where it returns 0 and die clause.

Did I set this up wrong?

EDIT

Curl on my localhost server

also the "Configure Command" is quite different(see below for localhost screen shot)

The remote server info mentions "curl" in this blob of text for Configure Command

回答1:

Codeigniter deletes $_REQUEST which is used by the Facebook PHP SDK to retrieve the OAuth code param.

The fix is to copy $_GET to $_REQUEST before your call to $facebook->getUser():

$_REQUEST += $_GET; 
$user = $facebook->getUser();

Thanks to this SO answer.



回答2:

Case 1 If User is logged in and still getting $user = 0

I faced this issue on different occasions but SDK issue is not happening to everyone. So I'm not sure what goes wrong here. But I dig in to it little bit and found solution as mentioned below.

SOLUTION : This worked for me after trying for many solutions for this issue.

In base_facebook.php file, find the makeRequest() method and check for following Line.

$opts = self::$CURL_OPTS; 

Immediately following it, add this line

$opts[CURLOPT_SSL_VERIFYPEER] = false;  

More details can be found here - http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/

Case 2 - If user is not Logged in

Try following

if($user_id) {
  // User is logged in do action here

} else {

  // No user, print a link for the user to login
  $login_url = $facebook->getLoginUrl();
  echo 'Please <a href="' . $login_url . '">login.</a>';

}