[eluser]Keloo[/eluser]
Hi, I'm trying to implement facebook authentication with codeigniter.
I've managed to login with facebook but I have a few problems. I can't logout from facebook properly. If I destroy the facebook session, it doesn't logout from the page, and vice versa.
Another problem is that I don't know how to store the facebook data into my database. I'm bulding an ecommerce site, so I need the users data, like first name, last name, email, id etc...
Here is my current code:
Home controller
Code:
class Home extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('Facebook_model');
$this->load->library('Layouts');
}
function index()
{
$fb_data = $this->session->userdata('fb_data');
$data = array(
'fb_data' => $fb_data
);
$this->layouts->set_title('Home');
$this->layouts->view('home', $data);
}
function account()
{
$fb_data = $this->session->userdata('fb_data');
if((!$fb_data['uid']) or (!$fb_data['me']))
{
$this->session->set_flashdata('error', 'Page access denied, login with your facebook account to access this page.');
redirect('home/index');
}
else
{
$data = array(
'fb_data' => $fb_data
);
$this->layouts->set_title('My Account');
$this->layouts->view('account', $data);
}
}
function logout()
{
$this->Facebook_model->fbLogout();
$this->session->sess_destroy();
redirect('home');
}
}
The model:
Code:
<?php
class Facebook_model extends CI_Model {
public function __construct()
{
parent::__construct();
$config = array(
'appId' => 'xxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxx',
'fileUpload' => true
);
$this->load->library('Facebook', $config);
$user = $this->facebook->getUser();
$profile = null;
if($user)
{
try {
$profile = $this->facebook->api('/me?fields=id,name,link,email');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
$fb_data = array(
'me' => $profile,
'uid' => $user,
'loginUrl' => $this->facebook->getLoginUrl(
array(
'scope' => 'email,user_birthday,publish_stream',
'redirect_uri' => site_url('home')
)
),
'logoutUrl' => $this->facebook->getLogoutUrl(),
);
$this->session->set_userdata('fb_data', $fb_data);
}
public function fbLogout()
{
$this->facebook->destroySession();
}
}
the views
Code:
<div>
<?php if(!$fb_data['me']): ?>
Please login with your FB account: <a href="<?php echo $fb_data['loginUrl']; ?>">login</a>
<!-- Or you can use XFBML -->
<?php else: ?>
<img src="https://graph.facebook.com/<?php echo $fb_data['uid']; ?>/picture" alt="" class="pic" />
<p>Hi <?php echo $fb_data['me']['name']; ?>,<br />
<?php echo anchor('home/account', 'Account');?> You can access the top secret page</a> or <?php echo anchor('home/logout', 'Logout'); ?></p>
<?php endif; ?>
</div>
1.So how can I logout from facebook and from the current page I'm in.
2. How can I store the user facebook data into a database.