CodeIgniter Forums
cookie will not set - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: cookie will not set (/thread-20291.html)



cookie will not set - El Forum - 07-04-2009

[eluser]Kyle Ellman[/eluser]
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:
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.


cookie will not set - El Forum - 07-04-2009

[eluser]Haloperidol[/eluser]
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.


cookie will not set - El Forum - 07-04-2009

[eluser]Kyle Ellman[/eluser]
Thanks.

But how would I do that?


cookie will not set - El Forum - 07-04-2009

[eluser]Haloperidol[/eluser]
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:
Code:
$autoload['libraries'] = array('session');

in a controller, lets name it user.php:
Code:
...
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:
Code:
...
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:
Code:
$user_nick = $this->session->userdata('nick_name');

and if you want to log out the user, youd do this in your user controller:
Code:
...
   $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).


cookie will not set - El Forum - 07-07-2009

[eluser]Kyle Ellman[/eluser]
Thanks.

It works now.