[英]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(). 我正在使用PHP中的搜索系统,它将搜索到的文本添加到数组中,并使用json_encode()将其放入cookie中。
The problem is: I need to check if the cookie already exists and, if not, create it. 问题是:我需要检查cookie是否已经存在,如果没有,则创建它。
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. 我可以创建cookie并获得它的价值,但我似乎无法找到一种方法来检查它是否已经在PHP代码中创建。
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。
//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() 使用get_cookie()
if (is_null(get_cookie('cookiename'))) {
//set yours cookie here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.