下面是另外一个稍微复杂一些的例子:
在这个例子中,输入表单的值被存储为一个称为email的cookie,然后在所有后续请求中,该值被自动获取以提前填充表单。该技术经常被需要用户输入登录名称和密码的Web站点来使用;通过在登录窗口用之前用户成功尝试的值自动提前填充用户名字段,它们为用户减少了一些按键操作。<?php if (!isset($_POST['email'])) { // if form has not been submitted // display form // if cookie already exists, pre-fill form field with cookie value ?> <html> <head></head> <body> <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> Enter your email address: <input type="text" name="email" value="<?php echo $_COOKIE['email']; ?>"> <input type="submit" name="submit"> <?php // also calculate the time since the last submission if ($_COOKIE['lastsave']) { $days = round((time() - $_COOKIE['lastsave']) / 86400); echo "<br /> $days day(s) since last submission"; } ?> </form> </body> </html> <?php } else { // if form has been submitted // set cookies with form value and timestamp // both cookies expire after 30 days if (!empty($_POST['email'])) { setcookie("email", $_POST['email'], mktime()+(86400*30), "/"); setcookie("lastsave", time(), mktime()+(86400*30), "/"); echo "Your email address has been recorded."; } else { echo "ERROR: Please enter your email address!"; } } ?> </body> </html>
这个例子也展示了你如何通过调用setcookie()多次为一个域设置超过一个的cookie。在上面的例子中,数据输入的时间被作为第二个cookie进行存储,然后用于计算两个连续登录之间的时间。
为了从客户端移除一个cookie,只要使用和你最初设置cookie时所用的语法相同的语法(除了过去的有效期之外)来调用setcookie()即可。这会引起cookie从客户端系统被移除。下面是一个例子:
阅读更多的关于cookies和setcookie()函数的信息,请访问:<?php // delete cookie setcookie("lastsave", NULL, mktime() - 3600, "/"); ?>
http://www.php.net/manual/en/features.cookies.php 和 http://www.php.net/manual/en/function.setcookie.php