Search code examples
phpfacebookauthenticationfacebook-php-sdkfacebook-authentication

Login with facebook is not working properly


I am using facebook api for using login functionality of facebook on my website. But there is a problem with it, it does not redirected to my website after login. It redirects to facebook home page. I don't know why it happens. My code is below:

This file name is logign_facebook.php

<?php

require 'facebook/facebook.php';
require 'config/fbconfig.php';
require 'config/functions.php';

$facebook = new Facebook(array(
            'app_id' => APP_ID,
            'app_seceret' => APP_SECRET,
            ));

$user = $facebook->getUser();

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }

    if (!empty($user_profile )) {
        # User info ok? Let's print it (Here we will be adding the login and registering routines)

        $username = $user_profile['name'];
             $uid = $user_profile['id'];
         $email = $user_profile['email'];
        $user = new User();
        $userdata = $user->checkUser($uid, 'facebook', $username,$email,$twitter_otoken,$twitter_otoken_secret);
        if(!empty($userdata)){
            session_start();
            $_SESSION['id'] = $userdata['id'];
 $_SESSION['oauth_id'] = $uid;

            $_SESSION['username'] = $userdata['username'];
            $_SESSION['email'] = $email;
            $_SESSION['oauth_provider'] = $userdata['oauth_provider'];
            header("Location: home.php");
        }
    } else {
        # For testing purposes, if there was an error, let's kill the script
        die("There was an error.");
    }
} else {
    # There's no active session, let's generate one
    $login_url = $facebook->getLoginUrl(array( 'scope' => 'email'));
    header("Location: " . $login_url);
}
?>

Please help me to fix this issue. Thanks


Solution

  • Facebook needs to know the URL to redirect back to when the user has logged in.

    You can pass this through the the getLoginUrl() function in the PHP SDK as below:

    $login_url = $facebook->getLoginUrl(array(
        'redirect_uri' => 'http://yoururlhere.com/logign_facebook.php',
        'scope'        => array('email')
    ));
    

    A full list of parameters for this function can be seen at https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl.