How to retrieve cookie value in CodeIgniter?

2019-01-17 23:48发布

问题:

I can print the session values in codeigniter by print_r($this->session->userdata); How can I print the cookies in codeigniter? I have just set a cookie:

$cookie = array(
          'name'   => 'test_cookie',
          'value'  => 'test',
          'domain' => '/',
          'secure' => TRUE
          );

$this->input->set_cookie($cookie); 

How can i print the above cookie?

回答1:

Look at the documentation: Codeigniter Cookie Helper Guide

It says that you should use $this->input->cookie() to retrieve a cookie:

$this->input->cookie('test_cookie', TRUE);


回答2:

This worked for me on localhost, security might need tightened for server

$this->load->helper('cookie');     
$cookie = array(
                    'name'   => 'data',
                    'value'  => '23',
                    'expire' =>  86500,
                    'secure' => false
                );
                $this->input->set_cookie($cookie); 
                var_dump($this->input->cookie('data', false));  

Expire needs to be numeric, removed path and set secure to false



回答3:

If you are using google chrome use inspect element to see if the cookie has been set... I think you can do it in FF, but I haven't used FF in a while... I only had one issue with cookies and that was I was setting domain to my live domain... So I have my cookie code like this:

        $this->load->helper('cookie');

         $cookie = array(
           'name'   => 'the_cookie',
           'value'  => 'test value here',
           'expire' => '15000000',
           'prefix' => ''
        );
        $this->input->set_cookie($cookie);

Here you can see it is showing up in Google Chrome "Inspect Element Tool"



回答4:

'secure' => TRUE

This does not allow me to fetch the cookie.


just set

'secure' => FALSE 

and see it may work.



回答5:

setting the security => TRUE will not allow to print the cookie value in local, it only grant access to secure connections only so it will not print anything in localhost for you unless you set the security => FALSE than using codeigniter CI_Input class you can get the value of cookie

$this->input->cookie('cookie_name', TRUE);  //with xss filtering 
$this->input->cookie('cookie_name');        //without xss filtering


回答6:

If the code mentioned below does not provide any output, then modify the application/config/config.php file and setting this:

$config['global_xss_filtering'] = TRUE;

$this->input->cookie('cookie_name', TRUE);

else just use this it will display the value

$this->input->cookie('cookie_name'); 


回答7:

Load the cookie helper with:

$this->load->helper('cookie');

Then retrieve your cooking with:

$cookieData = get_cookie("cookie_name");

Note, these are aliases to using the input class, you can also retrieve and set cookies like so:

$cookieData = $this->input->get_cookie("cookie_name");

Source http://ellislab.com/codeigniter/user-guide/helpers/cookie_helper.html