Sunday, June 16, 2013

Login with Facebook using PHP SDK 3.0

Login with Facebook is used by almost all the Websites these days to allow their visitors access them by using their Facebook login credentials. This makes a lot easier for the users, and it also increases your Website's user base. So today, we will be covering this tutorial for Login with Facebook using PHP SDK 3.0 and this is the easiest way to implement this.
For using this script you need to create an App on Facebook, and get an App ID and the App Secret Id for your Application. To create an App on Facebook, go to Facebook's Developers page.


Index file will have the Login with Facebook button, and once the session is created the Image and username from Facebook is also displayed here.

  index.php  


<?php 
session_start();
if(!isset($_SESSION['User']) && empty($_SESSION['User']))   { ?>
<div style="width:500px;margin:auto 0px;">
<a href="login.php">
<img src="images/facebook.png" style="cursor:pointer;"/></a></div>
<?php  
}  
else{
echo '<img src="https://graph.facebook.com/'. $_SESSION['User']['id'] .'/picture" width="30" height="30"/><div>'.$_SESSION['User']['name'].'</div>';
echo '<a href="'.$_SESSION['logout'].'">Logout</a>'
}
?>

To setup the script you need to add your App ID and App Secret ID into the config.php file.

  Config.php  


session_start();
//Facebook App Id and Secret Id
$appID = 'Your App Id';
$appSecret = 'Your App Secret';
/*
  URL to your website root will come in else condition 
  if you will run this on localhost, then also it will work
*/
if($_SERVER['HTTP_HOST']=='localhost')
{
$base_url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

else {
  $base_url='http://'.$_SERVER['HTTP_HOST'];
}


Other files include the API of Facebook, and its very simple to install this Application. For getting the required credentials from Facebook, we have used Facebook::getUser( ), Facebook::getLoginUrl( ) and Facebook::getLogoutUrl( ) methods.

For any problem do comment and we will help you as much as we can.


3 comments:

  1. Thanks for this wonderful script. I tried using on my local server and I encountered this: Fatal error: Uncaught exception 'Exception' with message 'Facebook needs the CURL PHP extension.'

    ReplyDelete
  2. Thank for this tutorial and you can see this geek to :
    Make Speech Recognition website

    ReplyDelete
  3. Nice blog...Very useful information is providing by ur blog. Great beginning php tutorials Very clear and helpful for beginners.

    ReplyDelete