Jaspreet Kaur
Jaspreet Kaur

Reputation: 123

Not able to Set cookie in Code-igniter

I'm not able to generate cookie the below code works only for only else part.

public function set(){
          $cookie = array(
              'name' => 'demo',
              'value' => 'hello i m saved cookie',
              'expire' => '86500'

          );//EOF array
          if($this->input->set_cookie($cookie))
          {
             $data = array( 'message' => 'cookie successfully set');
              $this->load->view('cookies_view',$data);
          }
          else{
              $data = array( 'message' => 'Something went wrong while creating cookie');
              $this->load->view('cookies_view',$data);
          }

Upvotes: 1

Views: 2265

Answers (3)

In my case after hours of debugging I realized that cookie_secure was set to true for local development.

So, do an easy check ;

If domain is not https and cookie_secure is set TRUE in config.php, cookies simply will not be set. Change to FALSE and it will be set in both http and https.

Upvotes: 0

Owais Aslam
Owais Aslam

Reputation: 1589

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

this function returns NULL thats why your condition is not working fine. your cookie is being set

use $this->input->cookie('your cookie name') to check your condition

public function set()
{
    $this->load->helper('cookie');
    $cookie = array(
      'name'   => 'demo',
      'value'  => 'Hello i m cookie',
      'expire' => '86500'
    );
    $this->input->set_cookie($cookie);
    if ($this->input->cookie('demo')) {
        $data['data'] = array('message' => 'cookie successfully set');
        $this->load->view('your view', $data);
    } else {
        $data['data'] = array('message' => 'Something went wrong while creating cookie');
        $this->load->view('your view', $data);
    }
}

Upvotes: 1

devpro
devpro

Reputation: 16117

Your value already stored in cookie, $this->input->set_cookie($cookie) this will only create the cookie. If you want to check cookie value set or not than you can use like that:

$cookie = array(
  'name'   => 'demo',
  'value'  => 'Hello i m cookies which saved in this broswer',
   'expire' => '86500',
);
$this->input->set_cookie($cookie);

if(isset(get_cookie('demo'))){ // check cookie value
  echo "success"; // replace with your code
}
else{
  echo "failed"; // replace with your code
}

get_cookie('demo') will return the cookie value.

You can also explore the CI Manual.

Make sure, you are using cookie helper in your file, you must need to include cookie helper:

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

Upvotes: 1

Related Questions