[eluser]leonardteo[/eluser]
I literally just worked it out... sharing and hopefully others will find this code here.
THis is very simple and I have not yet properly put in all the error checks, etc. It's here as a skeleton for others to figure it out..... I had searched high and low for how to do this and couldn't find an easy way (and I didn't want to use a pre-built library).
In your libraries directory, create a new file "autologin.php"
Here's the code in mine. Modify as you wish.
Code:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* The following hook checks if the user has a login cookie and processes that */
class Autologin {
var $CI;
//Constructor
function AutoLogin(){
$this->CI =& get_instance();
$this->CI->load->library('session');
$this->CI->load->helper('cookie');
$this->CI->load->database();
//if cookies are present, attempt login
if ($this->CI->session->userdata('logged_in') != TRUE){
$user_id = get_cookie('user_id');
$password = get_cookie('password');
//If no cookies set
if ($user_id == false || $password == false){
$this->logout();
}
$this->CI->load->model('User_model');
$user = $this->CI->User_model->get_user_by_id($user_id);
if ($user == false) {
//User doesn't exist, kill
$this->logout();
} else {
//attempt login
if ($user->password == $password){
//Successful login
//reset cookie
$user_cookie = array(
'name' => 'user_id',
'value' => $user->id,
'expire' => '100000',
);
$password_cookie = array(
'name' => 'password',
'value' => $user->password,
'expire' => '100000',
);
set_cookie($user_cookie);
set_cookie($password_cookie);
//set session data
$sessiondata = array('logged_in' => TRUE, 'user_id' => $user->id);
$this->CI->session->set_userdata($sessiondata);
} else {
//Foobar - kill
$this->logout();
}
}
}
}
function logout(){
delete_cookie('user_id');
delete_cookie('password');
$sessiondata = array('logged_in' => FALSE);
$this->CI->session->set_userdata($sessiondata);
}
}
?>
Then simply add 'autologin' to your config/autoload.php as one of the libraries loaded.
The above code assumes that you have a model called 'User_model' with a function get_user_by_id($user_id).
//Edit
Note that the password should be hashed. Never store plain text passwords in cookies. In my implementation above, I had stored hashed passwords in the database.
L.