Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting cookies not working in CodeIgniter

Tags:

codeigniter

I wnat to set cookie with a name csrf_cookie_name with a value from this function $this->security->get_csrf_hash(); but, it is not working.

I have this in my controller:

   $csrf_cookie_value = $this->security->get_csrf_hash();
   $this->input->set_cookie('csrf_cookie_name', $csrf_cookie_value);
   echo $this->input->cookie('csrf_cookie_name'); 
   die();

But it is not working and nothing is echoed out.

If I try only this:

 $csrf_cookie_value =  $this->security->get_csrf_hash();
 echo $csrf_cookie_value;

I works and a generated string is echoed out.

So, I assume that something within these next 2 lines is wrong:

$this->input->set_cookie('csrf_cookie_name', $csrf_cookie_value);
echo $this->input->cookie('csrf_cookie_name'); 

Thanks for your advice.

like image 714
Derfder Avatar asked Sep 16 '12 12:09

Derfder


3 Answers

You need to specify a life time for the cookie. 0 will be a session cookie and anything else will be added to time().

If you don't specify a life time, CI will interpret that you want to delete the cookie. And that's exactly what it does :)

$this->input->set_cookie('name', 'value', 0);    //expires when the browser window closes
$this->input->set_cookie('name', 'value', 3600); //expires in one hour
$this->input->set_cookie('name', 'value');       //will delete the cookie (if the cookie does not exist, you will not notice anything happening)
like image 163
Silviu G Avatar answered Oct 23 '22 11:10

Silviu G


The reason you are not getting a cookie echoed is because the $this->input->cookie() function reads directly from the global $_COOKIE array and $this->input->set_cookie() does not populate the $_COOKIE array immediately on the server. Instead, $this->input->set_cookie() queues the cookie to be sent back and stored in the browser. Only on the users' next HTTP request will you be able to re-observe this cookie.

Secondly, and perhaps more importantly, is that I think you are using the csrf cookie improperly. To protect against cross site request forgery only requires you to enable it and set it's properties in config/config.php. That is it. There is no need to read and write it in the controllers at all.

like image 7
Jordan Arseno Avatar answered Oct 23 '22 13:10

Jordan Arseno


The cookie is already there. You can consult via Javascript with:

$.cookie("<?php echo $this->config->item("csrf_cookie_name"); ?>");

I hope be useful.

like image 3
Alfonso Rubalcava Avatar answered Oct 23 '22 11:10

Alfonso Rubalcava