cookie 常用於識別用戶。cookie 是服務器留在用戶計算機中的小文件。每當相同的計算機通過浏覽器請求頁面時,它同時會發送 cookie。通過 php教程,您能夠創建並取回 cookie 的值。
如何創建 cookie?
setcookie() 函數用於設置 cookie。
注釋:setcookie() 函數必須位於 <html> 標簽之前。
語法
setcookie(name, value, expire, path, domain);例子
在下面的例子中,我們將創建名為 "user" 的 cookie,把為它賦值 "alex porter"。我們也規定了此 cookie 在一小時後過期
最簡單的cookie創建方法
<?php
echo( "cookie created? : " . setcookie("cookie_name", "cookie_data" ) );
?>
實例二cookies存數組
<?
setcookie("php[uid]", "1111111111111111", time()+3600);
setcookie("php[color]", "black", time()+3600);
setcookie("php[preference]", "english", time()+3600);if (isset ($php)) {
while (list ($name, $value) = each ($php)) {
echo "$name = $value<br>n";
}
}
?>
cookie刪除
<?php
setcookie ( "cookie_user", "test", time () + 60 * 60 * 24 * 30 );
setcookie ( "cookie_pass", md5 ( "test" ), time () + 60 * 60 * 24 * 30 );function logout() {
setcookie ( "cookie_user", "", time () + 60 * 60 * 24 * 30 );
setcookie ( "cookie_pass", "", time () + 60 * 60 * 24 * 30 );
}
logout ();
echo $_cookie ['cookie_user'] . "<br />";
echo "you have successfully logged out.";
?>
下面一個利用cookies記錄用戶名自動登錄函數實例
<?php
$globals['username'] = "test";
$globals['password'] = "test";
function validatelogin ($username, $password){
if (strcmp ($username, $globals['username']) == 0 && strcmp ($password, $globals['password']) == 0){
setcookie ("cookie_user", $username, time()+60*60*24*30);
setcookie ("cookie_pass", md5 ($password), time()+60*60*24*30);
return true;
} else {
return false;
}
}
if (validatelogin ("test","test")){
echo "successfully logged in.";
} else {
echo "sorry, invalid login.";
}
?>