How to create login with facebook in CodeIgniter website

Hey friends, we are going to create a facebook login script in PHP CodeIgniter framework. We will authenticate our users from facebook javascript login API and log them into our website.

Facebook login API does not work on HTTP sites recently, so you guys need a website with SSL to test our login with facebook script.

We will do it step by step.

1. Get an App Id from facebook

2. Create a database.

3. Create a login view in application/views folder.

4. Create a facebook javascript script in root/js folder.

5. Create a login model in application/models folder.

6. Create a login controller.

Step 1.

A. go to https://developers.facebook.com.

B. Create a new account if you never used it or just log in.

C. for new user click on get started button.

login with facebook integration image 1

;login with facebook integration second image

D. Click on next button to create a developer account. It will create a developer account from your existing account.

E. Change App Name that you want to keep.

login with facebook app integration image 3

F. Go to Settings->Basic settings and enter privacy & policy URL of your website. 

G. Choose a category for your website. Click on save changes and then click on the status live button to go live your app.

H. Go to the dashboard and click on facebook login button. 

I. it will ask you to enter your website URL. Enter your website URL and save it. Now we are ready to integrate login with Facebook on our website.

Step 2. Now we are going to create a MySql table for facebook login.

CREATE TABLE `tbl_facebook_login` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`facebook_id` INT NOT NULL,
`username` VARCHAR(255) NULL,
`password` VARCHAR(255) NULL,
`name` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NOT NULL,
`img` VARCHAR(255) NOT NULL,
`dateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`) 
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Step 3.Now we will Create a view called facebook.php  and put it at application/views/ folder.


<!DOCTYPE html>

<html>

<head>

	<title>
Facebook Login Example</title>

</head>

<body>

<button id="facebook-login" class="facebook">
Login With Facebook</button>

	<p id="status">
</p>

	<script src="<?php echo base_url('js/jquery');?>">
</script>

	
	<script>

	var base_url_value="<?php echo base_url();?>";
	</script>

	<script src="<?php echo base_url('js/facebook.js');?>">
</script>

</body>

</html>

Step 3.create a jquery file called facebook.js and put it at root/js folder. This js file will load facebook SDK at document loading time and bind the login event to our button. In this case, it will be `.facebook` class button in the facebook.php view file. Facebook js file contains a function called FB login. FB login calls facebook SDK to authenticate the user and if the user authenticates then it sends the response. We are using ajax function to send this data to server.ajax function sends data to check login() function of the Facebook controller.

window.fbAsyncInit = function() {
    // FB JavaScript SDK configuration and setup
    FB.init({
      appId      : 'xxxxxxxxxxxxxxx', // replace it with your FB App ID
      cookie     : true,  // enable cookies to allow the server to access the session
      xfbml      : true,  // parse social plugins on this page
      version    : 'v2.8' // use graph api version 2.8
    });
};

// Load the JavaScript SDK asynchronously
(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

// Facebook login with JavaScript SDK
function fbLogin() {
    FB.login(function (response) {
        if (response.authResponse) {
            // Get and display the user profile data
            getFbUserData();
        } else {
            document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
        }
    }, {scope: 'email'});
}

// Fetch the user profile data from facebook
function getFbUserData(){
    FB.api('/me', {locale: 'en_US', fields: 'id,first_name,last_name,name,email,link,gender,locale,picture'},
    function (response) {
        $.ajax({
		url: base_url_value+'Facebook/checkLogin',
		type:'POST',
		data:{name:response.name,email:response.email,source:'facebook',id:response.id,logintype:'seller',img:response.picture},
		success: function(data) 
              {
                var res=$.parseJSON(data);
                    if(res.response==="ok")
  { 
       window.open(base_url_value+"home","_self");
   
  }
else
{
      alert(data);
}
              }
	});
	
    });
	
}

// Logout from facebook

$(document).on('click','.facebook',function(){
	fbLogin();			   
	});

Step 4. create a modal called Facebook_login.php and put it in the application/models folder. Facebook model checks in DB if the user exists. it also inserts a new user or updates existing user.

   

class Facebook_model extends CI_Model
{
	 function __construct()
	{
		parent:: __construct();
		$this->load->database();
		
	}
	// for checking user email exist or not
	 function checkUser($fbid,$email)
	{
		$this->db->select("*");
		$this->db->where("facebook_id",$fbid);
		$this->db->where("email",$email);
		$res=$this->db->get("tbl_facebook_login");
		if($res->num_rows()>0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	 function insert_fb_user_data($id,$name,$email,$img)
	{
		if($this->db->insert("tbl_facebook_login",array("facebook_id"=>$id,"name"=>$name,"email"=>$email,"img"=>$img)))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	 function updateUser($id,$name,$email,$img)
	{
	$this->db->set("facebook_id",$id,true);
	$this->db->set("name",$name,true);
    $this->db->set("email",$email,true);
    $this->db->set("img",$img,true);
		if($this->db->update("tbl_facebook_login"))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	 function getDbId($email,$fbid)
	{
		$this->db->select("*");
		$this->db->where("facebook_id",$id);
		$this->db->where("email",$email);
		$res=$this->db->get("tbl_facebook_login");
		$data=$res->row_array();
		return $data["id"];
		
	}
	
}

   Step 5. Now we have to create controller file and put it at application/controllers folder. The Facebook controller handles ajax request from browser and calls model checkUser function to check user.If the user exists it updates user data and creates a session or if user does not exist then insert user data to DB which is obtained from facebook js login function.

or if anything goes wrong it's set $res variable to error. At last, sends a response to the browser. If everything goes right then jquery ajax redirects the user to hame page. 

class Facebook extends CI_Controlller
{
	 function __construct()
	{
		parent::__construct();
		$this->load->model("Facebook_model");
		$this->load->library("session");
	}
	 function start_session($id,$fbid,$email)
	{
		$data = array(
		'id'=>$id,
        'fbid'  => $fbid,
        'email'     => $email,
        'logged_in' => TRUE
);
	$this->session->set_userdata($data);	
  }

	function fb_login()
{
     $this->load->view("facebook");
}
	
	 function checkLogin()
	{
		$fbid=$this->input->post("id",true);
		$email=$this->input->post("email",true);
		$name=$this->input->post("name",true);
		$img-$this->input->post("img",true);
		if($this->Facebook_model->checkUser($fbid,$email))
		{
			if($this->Facebook_model->updateUser($id,$name,$email,$img))
			{
				$res="ok";
				$id=$this->Facebook_model->getDbId($email,$fbid);
				$this->start_session($id,$fbid,$email);
				
			}
			else
			{
				if($this->Facebook_model->insert_fb_user_data($id,$name,$email,$img))
				{
				$res="ok";
				$id=$this->Facebook_model->getDbId($email,$fbid);
				$this->start_session($id,$fbid,$email);	
				}
				else
				{
					$res="error";
				}
				
			}
		}
		else
		{
			$res="error";
		}
		echo json_encode($res);
	}
}

upload this whole script in your server and go to  https://yourwebsite/Facebook/fb_login   it will call the fb_login function which loads the facebook.php view we created. And click on login with facebook button. It will open a pop-up to authenticate and when authentication is successful you can redirect users where you want. Thanks!

 

Other posts