<?php
echo( "Cookie created? : " . setcookie("cookie_name", "cookie_data" ) );
?>
<html>
<head>
<title>Cookie</title>
</head>
<body>
</body>
</html>
如果要刪除 cookie只要設置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.";
?>
我們在開發中經常會用到cookie自動登錄,實例代碼如下:
<?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.";
}
?>