$apply_id=1111;
if(isset($_COOKIE['apply'])){
$apply_cookie=$_COOKIE['apply'];
@$apply_cookie=gzuncompress($_COOKIE['apply']);}
else{$apply_cookie=array();}
$apply_cookie = @explode(',', $apply_cookie);
if($apply_cookie === false){$apply_cookie = array();}
else{
$count=count($apply_cookie);
for($n=0; $n<$count; $n++){
if(!is_numeric($apply_cookie[$n])){unset($apply_cookie[$n]);}
}
}
//HAVE COOKIE
if(@in_array($apply_id, $apply_cookie)==TRUE){
echo "COOKIE=TRUE<BR>";
print_r($apply_cookie);
}
else{
//NO COOKIE,DB HAVE RECORDED
$db=TRUE; //QUERY HERE,SET TRUE OR FALSE FOR NOW
if($db==TRUE){
echo "COOKIE=FALSE; DB=TRUE";
$apply_cookie[]=$apply_id;
$apply_cookie=implode(',', $apply_cookie);
$apply_cookie=gzcompress($apply_cookie);
setcookie("apply", $apply_cookie, time()+3600*24*60);
}
else{
//NO COOKIE,NO RECORDED
echo "COOKIE=FALSE, DB=FALSE";
$apply_cookie[]=$apply_id;
$apply_cookie=implode(',', $apply_cookie);
$apply_cookie=gzcompress($apply_cookie);
setcookie("apply", $apply_cookie, $apply_cookie, time()+3600*24*60);
}
}
我设置了一个Cookie来检查用户是否已被应用。如果cookie有记录。它将跳过查询。如果没有cookie或没有记录而不是查询db并更新cookie。
gzcompress
(缩小版) - &gt; explode
(数组) - &gt; is_number
(仅允许数字) - &gt; in_array
(检查是否存在) )
这个足够安全吗? (之前我使用serialize
,但似乎有点不安全)
只检查cookie记录是否存在,如果不进行查询和更新cookie
答案 0 :(得分:2)
更好的解决方案是:
<?php
$apply_id = 1111;
switch (true) {
case !isset($_COOKIE['apply']):
case ($apply_cookie = @gzuncompress($_COOKIE['apply'])) === false:
case !is_array($apply_cookie = json_decode($apply_cookie)):
$apply_cookie = array();
break;
default:
$tmp = array();
foreach ($apply_cookie as $c) {
if (is_string($c) && is_numeric($c)) {
$tmp[] = $c;
}
}
$apply_cookie = $tmp;
}
if (in_array($apply_id, $apply_cookie)) {
// HAVE COOKIE
echo 'COOKIE = TRUE<br />'.PHP_EOL;
echo nl2br(print_r($apply_cookie, true));
} else {
$db = true;
// HAVE NO COOKIE
if ($db) {
// HAVE RECORDED
$apply_cookie[] = $apply_id;
setcookie('apply', gzcompress(json_encode($apply_cookie)), time()+3600*24*60);
echo 'COOKIE = FALSE, DB = TRUE<br />'.PHP_EOL;
} else {
// HAVE NO RECORDED
$apply_cookie[] = $apply_id;
setcookie('apply', gzcompress(json_encode($apply_cookie)), time()+3600*24*60);
echo 'COOKIE = FALSE, DB = FALSE<br />'.PHP_EOL;
}
}
注意:在输出之前您必须setcookie
。