2016-12-15 106 views
0
<html> 
    <head> 
     <meta charset="UTF-8"> 
     <title> Cookies </title> 
    </head> 
    <body> 
<h1> Cookies Concept </h1> 
     <form method="get" action="index.php"> 
      Enter Your Name: <input type="text" name="name"> 
      <input type="submit" name="done"> 
     </form> 
    </body> 
</html> 
<?php 
if(!empty($_GET['name']))  
{ 
    if(empty($_COOKIE['name'])) 
    { 
     setcookie('name',$_GET['name']."<br",time()+86400); 
    } 
    else 
    { 
     setcookie('name',$_GET['name'].<br>".$_COOKIE['name'],time()+86400);  
    }  
}  
if(isset($_COOKIE['name'])) 
{ 
     echo $_COOKIE['name']; 
} 
else 
{ 
    echo "Cookie cannot be set"; 
} 
?> 

我想打印輸入的最後十個名稱。如何做到這一點我不知道請幫幫我嗎?在PHP中使用cookie打印歷史記錄

+1

你不行。除非你把它們存放在別的地方。 Cookies存儲在用戶的計算機上,而不是服務器上。您無法同時訪問最後的10個Cookie,或者如果您這樣做(即,如果有超過10個併發用戶,將其全部餅乾調製並顯示在一個餅乾上將是一件非常麻煩的事情(您必須爲所有頁面上的所有用戶提供Cookie,並過濾出最後10個)。忘掉它,找到另一種方法來做你想做的事 – junkfoodjunkie

+0

@junkfoodjunkie的說法正確,另外我想補充說,任何人可以很容易地操作由'$ _COOKIE'函數設置的cookie,所以如果你真的想使用'$ _COOKIE'而不是會話,請確保你也設置允許的路徑,域和HttpOnly參數。 –

回答

0

如果你想保存來自同一用戶的最後10個,你可以使用serialize來保存一個數組到cookie中。但請記住,不會在用戶之間共享信息,因爲Cookie僅適用於該訪問者。 例如:

if(isset($_GET['name'])){ #get the name 
    $name = strip_tags($_GET['name']); 
    $names = []; # just names in case there is no names array 
    if(isset($_COOKIE['cookie'])){ #read cookie  
    $names = unserialize($_COOKIE['names']);  
    } 

    array_unshift($names, $name); #put the name in begging of the list 

    if(count($names) > 10){ #remove last entry if have more then 10 
    array_pop($names);  
    } 
    setcookie('names', serialize($names), time()+3600); 
} 

//to print just read cookie and 
foreach($names as $name){ 
    echo $name; 
}