Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$_COOKIE how to check as it is already set?

Tags:

php

cookies

Im wokring on a Webpage. The following code is in single.php.

First I'm counting everytime if someone opens a page/post + 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(); ?>

Why does it not work?

The goal is, so select the 3 IDs out of the Cookies on the index.php (Home) to select the last viewed posts.

If i refresh some post 3 times i have at the moment 3 times the same article on the home.

What am I doing wrong?

like image 651
Thebboii04 Avatar asked Nov 23 '25 05:11

Thebboii04


1 Answers

try this,

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

i hope it will be helpful.

like image 107
Dave Avatar answered Nov 24 '25 20:11

Dave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!