Part of the EllisLab Network
   
 
cookie will not set
Posted: 04 July 2009 12:54 PM   [ Ignore ]  
Summer Student
Avatar
Total Posts:  8
Joined  06-29-2009

Hello, I’m trying to set a cookie to make sure a user has a username and password to access the admin portion of the site.

I’m using this code:

function login()
    
{
        $data[
'error'] = '';
        
        if(
$_POST != NULL)
        
{
            $loggedin
= false;
            
$query = $this->db->get_where('users', array('user' => $_POST['user']));
            if (
$query->num_rows() > 0)
            
{
                
foreach ($query->result() as $row)
                
{
                    
if($row->password == $_POST['password'])
                        
$loggedin = true;
                
}
            }
            
            
if($loggedin)
            
{
                
                $host
= $_SERVER['HTTP_HOST'];
                if(
substr($host, 0, 4) == 'www.')
                    
$host = substr($host, 4, strlen($host)-1);
                
                
$cookie = array('name' => 'loggedin', 'value' => 'yipee!', 'expire' => '31556926', 'domain' => $host);
                
set_cookie($cookie);
                
//redirect('admin');
                
if(get_cookie('loggedin'))
                    
$data['error'] = 'cookie is set!';
                else
                    
$data['error'] = 'cookie not set';
            
}
            
else
            
{
                $data[
'error'] = '<h3 style="color:red">ERROR: Wrong username/password combination</h3>';
            
}
        }
        
        $data[
'title'] = $this->info_model->get_info('title');
        
$this->load->view('admin/login', $data);
    
}

When I try login, I always get the “cookie not set” message, telling me that the password is correct, and $logged in is getting set to true, but the cookie is simply not setting.

Any help would be appreciated.

Thanks.

Profile
 
 
Posted: 04 July 2009 01:24 PM   [ Ignore ]   [ # 1 ]  
Summer Student
Total Posts:  18
Joined  07-03-2009

Cookies are transferred in the http headers back and forth (at http request from the client and http response to the client). So you cant set a cookie and read it back on the same page.
also you might want to stick to storing login variables in sessions instead of cookies and just send the session id in the cookie for security reasons.

Profile
 
 
Posted: 04 July 2009 01:28 PM   [ Ignore ]   [ # 2 ]  
Summer Student
Avatar
Total Posts:  8
Joined  06-29-2009

Thanks.

But how would I do that?

Profile
 
 
Posted: 04 July 2009 01:50 PM   [ Ignore ]   [ # 3 ]  
Summer Student
Total Posts:  18
Joined  07-03-2009

you could use the built in session library in codeigniter and you dont have to worry about managing the cookies altogether. this would be and example:

first, if you plan to use sessions you would auto-load it in the system/application/config/autoload.php:

$autoload['libraries'] = array('session');

in a controller, lets name it user.php:

...
function
login()
{
   $this
->load->model('User_model'); // load the model that does the actual sql query
   
$user_data = $this->User_model->user_registered(); // store its return data in a variable
   
if ($user_data != FALSE) { // check if the model function returned false
    
$this->session->set_userdata('logged_in','true'); // store whatever you want in session vars...
        
$this->session->set_userdata('user_id',$user_data->id);
        
$this->session->set_userdata('user_nick',$user_data->nick_name);
        
$this->session->set_userdata('user_role',$user_data->role);
    
redirect('to_whatever_page_if_successful', 'refresh');
   
} else {
    $this
->session->unset_userdata(); // just to be sure
    
$this->session->set_flashdata('login_error', 'true'); // or you can use the form helpers
    
redirect('back_to_login_page', 'refresh');
   
}
}
...

in the model User_model.php, the corresponting function would be:

...
function
user_registered()
{
   $query
= $this->db->query("SELECT * from users where nick_name = ".$this->db->escape($this->input->post('nick_name'))." AND password = ".$this->db->escape($this->input->post('password'))." limit 1");
   if (
$query->num_rows() > 0) {
    
return $query->row();
   
} else {
    
return FALSE;
   
}
}
...

in this case only a session id will be set in the cookie (right when the user loads any of your pages for the first time) and if the login is valid, you can access the session variables anywhere in this fashion:

$user_nick = $this->session->userdata('nick_name');

and if you want to log out the user, youd do this in your user controller:

...
   
$this->session->sess_destroy(); // will destroy all the stored session variables for this user
   
...

btw, set_userdata(‘whatever’) will set a session variable that can be accessed as long as the session is alive, and set_flashdata(‘whatever’) will set a session variable only for the next pageload and then it gets destroyed (good for temporary stuff like validation errors).

Profile
 
 
Posted: 07 July 2009 04:51 PM   [ Ignore ]   [ # 4 ]  
Summer Student
Avatar
Total Posts:  8
Joined  06-29-2009

Thanks.

It works now.

Profile
 
 
   
 
 
Post Marker Legend
New Topic New posts Hot Topic Hot Topic with new posts New Poll New Poll Moved Topic Moved Topic Sticky Topic Sticky topic
Old Topic No new posts Hot Old Topic Hot Topic with no new posts Old Poll Old Poll Closed Topic Closed Topic Announcement Announcements
Theme
Change Theme
Visitor Statistics
The most visitors ever was 819, on March 11, 2010 10:15 AM
Total Registered Members: 119685 Total Logged-in Users: 38
Total Topics: 125882 Total Anonymous Users: 3
Total Replies: 662354 Total Guests: 400
Total Posts: 788236    
Members ( View Memberlist )