2017-06-12 57 views
1

服務器是我的電腦(http://127.0.0.1/),我檢查Cookies是否被創建。

這是我的代碼。此代碼通過表單獲得「selected_item_no」,並創建或覆蓋cookie。看看與//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)是這樣的。換句話說,$_COOKIE["cart_item_no"]被定義爲$_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" } 

它只是不斷增長。

我不知道如何解決這個問題...

+0

你爲什麼要設置3個餅乾?你爲什麼不使用會話? – rtfm

+0

編輯你的代碼片段,並顯示你在哪裏使用'var_dump'和你在哪裏使用'isset()'。 – SaidbakR

+2

它應該是'$ _COOKIE [「cart_item_no」] [$ ii]',而不是'$ _COOKIE [「cart_item_no [$ ii]」]'。 – Siguza

回答

1

你在做數組下標錯誤。
正確的語法是$_COOKIE["cart_item_no"][$ii],而不是$_COOKIE["cart_item_no[$ii]"]