Facebook Login With Php

Login in php using facebook


In website login with facebook is little bit tricky. You have need following things to do if you want to login using facebook


Step 1 Grab facebook developers id and App Secret



First got to the https://developers.facebook.com/ and create new id and app key for the facebook sdk which will be used while accessing data from facebook site .


Step 2 Get facebook sdk


* Now create a facebook_login_folder in you xampp or wamp or on your server.
*Now go to the https://github.com/facebook/php-graph-sdk and grab the facebook software developm
ent toolkit from there and put the facebook folder in facebook_login_folder.


Step 3 Create database


* Now go to the mysql database and create a database and import the following sql command or make a table for collecting user data from facebook.






Step 4 Create userclass.php file


Now create a userclass.php file this file will contain a operation file that file will help inserting and updating data in mysql database. Kindly enter your database name and your password , database name correctly as in comments.
<?php

class User {

    private $dbHost     = "localhost";  //Enter your hostname

    private $dbUsername = "root";       // Enter your username

    private $dbPassword = "";           // Enter your host password

    private $dbName     = "facebook_login";  // Enter your database name

    private $userTbl    = 'users';          

  

    function __construct(){

        if(!isset($this->db)){

            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword,
            $this->dbName);

            if($conn->connect_error){

                die("Failed to connect with MySQL: " . $conn->connect_error);

            }else{

                $this->db = $conn;

            }

        }

    }

  

    function checkUser($userdetails = array()){

        if(!empty($userdetails)){

          

            $preQuery = "SELECT * FROM ".$this->userTbl."
            WHERE a_provider = '".$userdetails['a_provider']."' AND 
            oauth_uid = '".$userdetails['oauth_uid']."'"; 
           // Check whether user  already exists in table

            $preResult = $this->db->query($preQuery);

            if($preResult->num_rows > 0){

              

                $query = "UPDATE ".$this->userTbl." 
                SET first_name = '".$userdetails['first_name']."', 
                last_name = '".$userdetails['last_name']."', 
                email = '".$userdetails['email']."', 
                gender = '".$userdetails['gender']."', 
                locale = '".$userdetails['locale']."', 
                cover = '".$userdetails['cover']."',
                picture = '".$userdetails['picture']."', 
                link = '".$userdetails['link']."', 
                modified = NOW() WHERE a_provider = '".$userdetails['a_provider']."' AND
      oauth_uid = '".$userdetails['oauth_uid']."'";  // Update table if user already exists

                $update = $this->db->query($query);

            }else{

                // Insert  data

                $query = "INSERT INTO ".$this->userTbl." 
                SET a_provider = '".$userdetails['a_provider']."',
                oauth_uid = '".$userdetails['oauth_uid']."', 
                first_name = '".$userdetails['first_name']."', 
           last_name = '".$userdetails['last_name']."', email = '".$userdetails['email']."',
             gender = '".$userdetails['gender']."', locale = '".$userdetails['locale']."',
           cover = '".$userdetails['cover']."', picture = '".$userdetails['picture']."',
              link = '".$userdetails['link']."', created = NOW(), modified = NOW()";

                $insert = $this->db->query($query);

            }

          

            $result = $this->db->query($preQuery);

            $userdetails = $result->fetch_assoc();

        }

      

        return $userdetails;

    }

}

?>


Step  5 Create facebook configuration file (fbconfig.php)


Now in this step create the fbconfig.php file this file will autoload the necessery files required from facebook sdk . You need to put your developer id and your facebook app secrete key in the code and also specify the proper path to your facebook sdk kit as shown in comments.

<?php

if(!session_id()){

    session_start();

}


require_once __DIR__ . '/facebook/autoload.php';   // Provide path of your sdk here

// These are librabies of facebook required during datatransfer operations.

use Facebook\Facebook;

use Facebook\Exceptions\FacebookResponseException;

use Facebook\Exceptions\FacebookSDKException;


/*

 * Sdk configuration

 */

$appId         = '*********'; //Provide your developer id or facebook id here

$appSecret     = '*********'; //provide your secrete app key there

$redirectURL   = 'http://localhost/facebook_login'; //Callback URL

$fbPermissions = array('email');

$fb = new Facebook(array(

    'app_id' => $appId,

    'app_secret' => $appSecret,

    'default_graph_version' => 'v2.10',

));



$helper = $fb->getRedirectLoginHelper();



try {

    if(isset($_SESSION['facebook_access_token'])){

        $accessToken = $_SESSION['facebook_access_token'];

    }else{

          $accessToken = $helper->getAccessToken();

    }

} catch(FacebookResponseException $e) {

     echo 'Graph returned an error: ' . $e->getMessage();

      exit;

} catch(FacebookSDKException $e) {

    echo 'Facebook returned an error: ' . $e->getMessage();

      exit;

}



?>


Step 6 Create index file or your login page.


Now create your index file that will contain your home page form if facebook find any error it will redirect you to on this page
<?php

// Include FB config file

require_once 'fbConfig.php';

require_once 'User.class.php';



if(isset($accessToken)){

    if(isset($_SESSION['facebook_access_token'])){

        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);

    }else{

        $_SESSION['facebook_access_token'] = (string) $accessToken;

        $oAuth2Client = $fb->getOAuth2Client();

        $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken
($_SESSION['facebook_access_token']);

        $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;

        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);

    }

     if(isset($_GET['code'])){

        header('Location: ./'); //redirect to home page

    }

  

    try { //grabbing facebook profile information

        $profileRequest = $fb->get('/me?fields=name,first_name,last_name,email,link,gender,
        locale,cover,picture');

        $fbUserProfile = $profileRequest->getGraphNode()->asArray();

    } catch(FacebookResponseException $e) {

        echo 'Graph returned an error: ' . $e->getMessage();

        session_destroy();

        header("Location: ./"); //redirect back to login

        exit;

    } catch(FacebookSDKException $e) {

        echo 'Facebook SDK returned an error: ' . $e->getMessage();

        exit;

    }

    $user = new User();

    $fbuserdetails = array(

        'a_provider'=> 'facebook',

        'oauth_uid'     => $fbUserProfile['id'],

        'first_name'    => $fbUserProfile['first_name'],

        'last_name'     => $fbUserProfile['last_name'],

        'email'         => $fbUserProfile['email'],

        'gender'        => $fbUserProfile['gender'],

        'locale'        => $fbUserProfile['locale'],

        'cover'         => $fbUserProfile['cover']['source'],

        'picture'       => $fbUserProfile['picture']['url'],

        'link'          => $fbUserProfile['link']

    );

    $userdetails = $user->checkUser($fbuserdetails);

  $_SESSION['userdetails'] = $userdetails;

   $logoutURL = $helper->getLogoutUrl($accessToken, $redirectURL.'logout.php');

   if(!empty($userdetails)){

        $out  = '<h2 style="color:#999999;">Facebook Profile Details</h2>';

        $out .= '<div style="position: relative;">';

        $out .= '<img src="'.$userdetails['cover'].'" />';

        $out .= '<img style="position: absolute; top: 90%; left: 25%;" 
         src="'.$userdetails['picture'].'"/>';

        $out .= '</div>';

        $out .= '<br/>Facebook ID : '.$userdetails['oauth_uid'];

        $out .= '<br/>Name : '.$userdetails['first_name'].' '.$userdetails['last_name'];

        $out .= '<br/>Email : '.$userdetails['email'];

        $out .= '<br/>Gender : '.$userdetails['gender'];

        $out .= '<br/>Locale : '.$userdetails['locale'];

        $out .= '<br/>Logged in with : Facebook';

        $out .= '<br/>Profile Link : <a href="'.$userdetails['link'].'" target="_blank">
        Click to visit Facebook page</a>';

        $out .= '<br/>Logout from <a href="'.$logoutURL.'">Facebook</a>';

    }else{

        $out = '<h3 style="color:red">Some problem occurred, please try again.</h3>';

    }

}else{

   $loginURL = $helper->getLoginUrl($redirectURL, $fbPermissions);

   $out = '<a href="'.htmlspecialchars($loginURL).'"><h2>
  Click here to login with facebook</h2></a>';

}

?>

<html>

<head>

<title>Login in website with Facebook</title>

</head>

<body>

    <div><?php echo $out; ?></div>    //display login url

</body>

</html>




Step 7 Logout form ( logout.php )


Create a logout.php file that will remove all your data or that will unset all the data from session variables.
<?php

require_once 'fbConfig.php';    //remove all your token keys fb config data from session

unset($_SESSION['facebook_access_token']);

unset($_SESSION['userData']);

header("Location:index.php");

?>



I hope you are now able to login using facebook if have any query or any help you may leave a comment in the comment box.

No comments:

Post a Comment