cookie 是由服务器发送到浏览器的变量,cookie 通常是服务器嵌入到用户计算机中的小文本文件,每当计算机通过浏览器请求一个页面,就会发送这个 cookie,实例代码如下:
- <?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.";
- }
- ?>
|