Search code examples
phparrayscookiesunset

PHP $_COOKIE get cookie with preset variable


SOLUTION:

$_COOKIE was replacing periods with underscores.

str_replace('.','-',$cookie_name); 

PROBLEM

I am setting a cookie like this.

$cookie_name = '_visited-'.$user_ip.'-'.$visted_link; 
setcookie($cookie_name,'visited',time() + (86400 * 30), "/");
header('Location: '.$_SERVER['REQUEST_URI']);
exit;

then trying to see if cookie is set and unlink it from links array like this.

foreach($links['unique'] as $link){
    $cookie_name = '_visited-'.$user_ip.'-'.$link; 
    if(isset($_COOKIE[$cookie_name])){
        if(($key = array_search($l, $links['unique'])) !== false) {
            unset($links['unique'][$key]);
        }
    }
}

odd thing is that even though the cookie is clearly set in the foreach using isset I am unable to detect that the cookie exist so I am unable to remove the visited link.


Solution

  • ok so found the issue. I was putting user IP in as part of the cookie name. The . was being replaced by _ so just went ahead and replaced all . with - when setting the cookie. Works perfectly as I had intended now.