cookie就像是php中的session一樣,只是一個在客戶端一個是在服務器端了,下面我來詳細介紹php中setcookie對cookie設置與刪除代碼。
setcookie()語法
setcookie (PHP 3, PHP 4, PHP 5)
setcookie -- 發送一個 cookie 信息
說明:bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure]]]]] )
例
寫cookie
代碼如下 復制代碼<?php
$value = 'something from somewhere';
setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600); /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);
?>
讀cookie
代碼如下 復制代碼<?php
// Print an individual cookie
echo $_COOKIE["TestCookie"];
echo $HTTP_COOKIE_VARS["TestCookie"];
// Another way to debug/test is to view all cookies
print_r($_COOKIE);
?>
刪除cookie
<?php
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);
?>
由於cookie與HTTP的特定方式,你必須在你輸出任何文本前,傳送出所有的cookie。否則PHP會給出警告,並且cookie也不會被傳送。因此,這樣做是正確的:
<?php
setcookie(’name’, ‘jeff’);
echo “Hello Everyone!”;
?>
以下是錯誤地:
代碼如下 復制代碼<?php
echo “Hello Everyone!”;
setcookie(’name’, ‘jeff’);
?>