2010-05-11 96 views
1

我決定創建一個最近的查看框,允許用戶查看之前他們點擊了哪些鏈接。每當他們點擊張貼時,張貼的ID就被存儲在一個cookie中,並顯示在最近的視圖框中。如何使用cookie來存儲用戶最近的網站歷史記錄(PHP)?

在我的ad.php中,我有一個definerecentview函數,用於在cookie中存儲帖子的ID(以便稍後嘗試從數據庫中獲取帖子的信息,例如標題,價格)。我如何爲此創建一個cookie數組?

 **EXAMPLE:** user clicks on ad.php?posting_id='200' 

    //this is in the ad.php 
    function definerecentview() 
    { 

     $posting_id=$_GET['posting_id']; 
     //this adds 30 days to the current time 
     $Month = 2592000 + time(); 
     $i=1; 
     if (isset($posting_id)){ 
         //lost here 
      for($i=1,$i< ???,$i++){    
       setcookie("recentviewitem[$i]", $posting_id, $Month); 
      } 
     } 
    } 


    function displayrecentviews() 
    { 
     echo "<div class='recentviews'>"; 
     echo "Recent Views"; 
     if (isset($_COOKIE['recentviewitem'])) 
     { 
      foreach ($_COOKIE['recentviewitem'] as $name => $value) 
      { 
       echo "$name : $value <br />\n"; //right now just shows the posting_id 
      } 
     } 
     echo "</div>"; 
    } 

如何使用一個for循環或foreach循環,使它只要用戶點擊廣告,這使得在cookie中的數組?所以它會像..

1. clicks on ad.php?posting_id=200 --- setcookie("recentviewitem[1]",200,$month); 
2. clicks on ad.php?posting_id=201 --- setcookie("recentviewitem[2]",201,$month); 
3. clicks on ad.php?posting_id=202 --- setcookie("recentviewitem[3]",202,$month); 

然後在displayrecentitem函數,我只是回聲然而許多餅乾被設置?

我完全失去了創建一個設置cookie的for循環。任何幫助,將不勝感激

回答

2

不要設置多個cookie - 設置一個包含數組(序列化)。當你附加到數組時,首先讀入現有的cookie,添加數據,然後覆蓋它。

// define the new value to add to the cookie 
$ad_name = 'name of advert viewed'; 

// if the cookie exists, read it and unserialize it. If not, create a blank array 
if(array_key_exists('recentviews', $_COOKIE)) { 
    $cookie = $_COOKIE['recentviews']; 
    $cookie = unserialize($cookie); 
} else { 
    $cookie = array(); 
} 

// add the value to the array and serialize 
$cookie[] = $ad_name; 
$cookie = serialize($cookie); 

// save the cookie 
setcookie('recentviews', $cookie, time()+3600); 
+0

好吧謝謝。 我只是保持我的第二個功能(displayrecentviews)相同並將我的第一個功能更改爲此? – ggfan 2010-05-11 19:33:12

+0

按照我的例子,當你讀取cookie時,你必須反序列化數組。這個例子可能不完全符合你的需求,但你可以將任何數據放入一個序列化的數組中,並將它存儲在一個cookie中。 – 2010-05-11 19:49:07

0

您不應該爲每個最近的搜索創建一個cookie,而應該只使用一個cookie。試試下面這個想法:

  • cookie中的每個值必須是 從另一個與 獨特的分離器分離,可以使用., ;|。 E.g:200,201,202

  • 當 檢索從cookie中的數據, 如果存在的話,使用 explode(',',CookieName);,所以你會 與ID數組結束。

  • 當添加 數據到cookie,你可以做, 再次,explode(',',CookieName);到 創建一組ID,然後檢查 新ID不使用 in_array();,然後將值 添加到陣列中該陣列使用array_push();。 然後使用 implode(',',myString);將數組內爆並將 myString寫入cookie。

就是這樣。

相關問題