2016-07-07 53 views
3

我正在网页上。以下代码在single.php中。

首先,如果有人打开了一个网页/后+ 1

<?php 
//The cookie Besuche neeeds to be under 3 
if (isset($_COOKIE['besuche'])){ 
    if ($_COOKIE['besuche'] >= 3){ 
    //If its more than 3, cookie resets to 1 
    $besuche_anz = 1; 
    $_COOKIE['besuche'] = $besuche_anz; 
    }else{ 
    //If its less than 3. cookie + 1 
    $_COOKIE['besuche'] = $_COOKIE['besuche'] + 1; 
    $besuche_anz = $_COOKIE['besuche']; 
    } 
}else{ 
    //Cookie is not set 
    $besuche_anz = 1; 
} 

//write cookie "besuche" 
setcookie("besuche", $besuche_anz, time() + (86400 * 30), "/"); 

//Here starts my problem... I want so write three cookies: cookie_id1, cookie_id2, cookie_id3. But all cookies should be diffrent. So they sould not have the same ID --> get_the_id() 

$cookie_value = get_the_id(); 
setcookie("cookie_id".$besuche_anz, $cookie_value, time() + (86400 * 30), "/"); 
//Only if $cookie_value has the same ID --> Do nothing, else setcookie 
if ($cookie_value == $_COOKIE["cookie_id1"]){}else{ 
    setcookie("cookie_id".$besuche_anz, $cookie_value, time() + (86400 * 30), "/"); 
} 

//Only if $cookie_value has the same ID --> Do nothing, else setcookie 
if ($cookie_value == $_COOKIE["cookie_id1"] || $_COOKIE["cookie_id2"]){}else{ 
    setcookie("cookie_id".$besuche_anz, $cookie_value, time() + (86400 * 30), "/"); 
} 

get_header(); ?> 

它为何不工作,我就指望每次?

目标是,从index.php(主页)上的Cookies中选择3个ID来选择最后查看的帖子。

如果我刷新一些帖子3次,我现在有3次同一篇文章在家里。

我在做什么错?

+0

对'$ _COOKIE'的更改实际上并不改变cookie,你必须每次都执行'setcookie'。 – apokryfos

回答

2

试试这个,

if(!isset($_COOKIE[$cookie_name])) 
    { 
     setcookie('cookie_name', $cookie_value, time() + (86400 * 30), "/"); 
    } 

我希望这会有所帮助。

+0

感谢您的答案,但我不想检查cookie设置... 我用魔杖来比较文章的ID(get_the_id();)与cookie_id1。只有当它们具有不同的值时,才会写入新的cookie。 但是非常感谢! – Thebboii04

相关问题