Facebook App
- Create a new Facebook App.
- Get the APP ID and APP Secret.
- After creating your App, click Settings.
- In the Basic section, add your domain name in the App Domains.
- Click on Add Platform and select Website and add the same domain you added in step 4 but with http:// as prefix in Site URL.
- To test the app localhost, you need to create a Virtual Host.
Installing
- Download the Facebook PHP SDK.
- Download CodeIgniter.
- Extract CodeIgniter.
- Extract the Facebook SDK and
- Rename facebook.php to Facebook.php
- Add the following at the beginning of the Facebook.php file, right after the php opening tag.
1
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
- Create a directory named “facebook” in application/libraries and copy the 3 files in the Facebook SDK extracted directory to application/libraries/facebook in CodeIgniter.
- In CodeIgniter, create a file facebook.php in application/config directory with the following content (add your application Id and secret key of the Facebook app):
1234567
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['appId'] = [App ID];
$config['secret'] = [App secret];/* End of file facebook.php */
/* Location: ./application/config/facebook.php */
- Open your application/config/config.php file and make sure $config[‘allow_get_array’] is set to true.
How this example will work with OAuth
In OAuth, the procedure is the following:
- The user clicks on a sign in link on your website.
- User is redirected to Facebook, enter his credentials, authorize your app.
- Facebook then redirects the user back to your application with data.
Creating controller and view files
1. Create a controller (in this example Auth Controller). In your controller add the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Auth extends CI_Controller { $userId = $this->facebook->getUser();// If user is not yet authenticated, the id will be zeroif($userId == 0){ // Generate a login url $data[‘login_url’] = $this->facebook->getLoginUrl(array(‘scope’=>’email,user_about_me’)); $this->load->view(‘main_index’, $data); } else { // Get user’s data and print it $user = $this->facebook->api(‘/me’); echo ‘<pre>’; print_r($user); } |
2. Create a view, called main_index.php in your views directory.
1
|
<a href="<?php echo $login_url; ?>">Click here to login using Facebook</a> |
3. Now load the function facebook of Auth Controller in your browser.
If the user authenticates your app, you will get the user’s data.