简体   繁体   中英

Check if cookie exists in CodeIgniter

I'm using a search system, in PHP, that adds the text searched to an array and put it inside a cookie using json_encode().

The problem is: I need to check if the cookie already exists and, if not, create it.

I'm using the following code to simply verify if it exists but without success:

{
        $search     = $this->input->post('search_text');
        $types      = $this->input->post('search_type');
        $checkboxes = "";
        if(!empty($types))
        {
            foreach($types as $v)
                $checkboxes = $v.",";
        }

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

        //cookie's array
        $search_history = array();
        array_push($search_history, $search);

        //cookie check 1
        if(get_cookie('search')!=''){
            echo "cookie exists";
        }else
            echo "cookie doesn't exist";

        // set cookie 
        $cookie = array(
            'name'   => 'search',
            'value'  => json_encode($search_history),
            'expire' => time()+86500
        );
        set_cookie($cookie);

        //cookie check 2
        if(get_cookie('search')!=''){
            echo "cookie exists";
        }else
            echo "cookie doesn't exist";

        //echo get_cookie('search');

        //redirect('search/'.urlencode($search).'/'.urlencode($checkboxes)); 
    }

I can create the cookie and get it's value, but I can't seem to find a way to check if it's already created in PHP code.

Have already tried with:

if(get_cookie('search')!='')

,

if(get_cookie('search')!=null)

and with

if(get_cookie('search'))

but neither of those seem to work.


EDIT:

As suggested, I'm now using this and it doesn't create the cookie.

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

        //cookie's array
        $search_history = array();
        array_push($search_history, $search);

        if(cookie('search') == false){
            // set cookie 
            $cookie = array(
                'name'   => 'search',
                'value'  => json_encode($search_history),
                'expire' => time()+86500
            );
            set_cookie($cookie);
        }            

Final EDIT

Problem solved.

 //checks if the cookie exists
        if($this->input->cookie('cookiename')!=''){
            //exists
        }

use get_cookie()

if (is_null(get_cookie('cookiename'))) {
 //set yours cookie here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM