Ernest B
Ernest B

Reputation: 13

isset($_COOKIE) not working

Server is my computer (http://127.0.0.1/) and I checked Cookies are created.

This is my code. This code got "selected_item_no" by form, and create or overwrite cookie. Look at the line commented with //Issue is here:

<?php
session_start();
$selected_item_no=$_POST["selected_item_no"];
$search_item=$_POST["search_item"];
$search_text=$_POST["search_text"];
$isadded = 0;
if((trim($selected_item_no)!="")) {
    if (isset($_COOKIE["maxcount"])) {
      $maxcount = $_COOKIE["maxcount"];
      for($ii=1;$ii<=$maxcount;$ii++){
       ////////// ISSUE IS HERE 
        if(isset($_COOKIE["cart_item_no[$ii]"])){ // this line doesn't work
        /////////
          $temp_item_no = $_COOKIE["cart_item_no[$ii]"];
          if(trim($temp_item_no)===trim($selected_item_no)){
            $temp_item_count = $_COOKIE["cart_item_count[$ii]"] + 1;
            setcookie("cart_item_count[$ii]", $temp_item_count, time()+3600, "/");
            $temp_arr_i = $ii;
            $isadded = 1;
            break;
          }
        }
      }
      if($isadded == 0){
        $maxcount = $ii;
        setcookie("maxcount", $maxcount, time()+3600, "/");
        setcookie("cart_item_no[$maxcount]", $selected_item_no, time()+3600, "/");
        setcookie("cart_item_count[$maxcount]", 1, time()+3600, "/");
        $temp_arr_i = $ii;
      }
    } else {
      $maxcount = 1;
      setcookie("maxcount", $maxcount, time()+3600, "/");
      setcookie("cart_item_no[$maxcount]", $selected_item_no, time()+3600, "/");
      setcookie("cart_item_count[$maxcount]", 1, time()+3600, "/");
      $temp_arr_i = $maxcount;
    }
  }
  $temp_count_tt = $_COOKIE["cart_item_count[$temp_arr_i]"];
?>
<html>
<head>

<?php
include("./style.php");
?>

</head>
<body>
<?php 
  if((trim($selected_item_no)!="")) {
    echo("$selected_item_no is added at $temp_arr_i . count: $temp_count_tt. isadded: $isadded.<br>");
    var_dump($_COOKIE);
  }
?>

var_dump($_COOKIE) is like this. In other words, $_COOKIE["cart_item_no"] is defined as array in the $_COOKIE!

array(4) { ["PHPSESSID"]=> string(32) "819d97292666fbe9201ba52219204324" ["cart_item_no"]=> array(7) { [1]=> string(3) "b01" [2]=> string(3) "b02" [3]=> string(3) "b01" [4]=> string(3) "b01" [5]=> string(3) "b01" [6]=> string(3) "b02" [7]=> string(3) "b02" } ["cart_item_count"]=> array(7) { [1]=> string(1) "1" [2]=> string(1) "1" [3]=> string(1) "1" [4]=> string(1) "1" [5]=> string(1) "1" [6]=> string(1) "1" [7]=> string(1) "1" } ["maxcount"]=> string(1) "7" }

It just keeps growing.

I don't know how to solve this problem...

Upvotes: 1

Views: 518

Answers (1)

Siguza
Siguza

Reputation: 23850

You're doing array subscripting wrong.
The correct syntax is $_COOKIE["cart_item_no"][$ii], not $_COOKIE["cart_item_no[$ii]"].

Upvotes: 1

Related Questions