php setcookie详解用法

cookie 常用于识别用户,cookie 是服务器留在用户计算机中的小文件,每当相同的计算机通过浏览器请求页面时,它同时会发送 cookie,通过 php,您能够创建并取回 cookie 的值.

如何创建 cookie?

setcookie() 函数用于设置 cookie.

注释:setcookie() 函数必须位于 <html> 标签之前.

语法:setcookie(name,value,expire,path,domain);例子.

在下面的例子中,我们将创建名为 "user" 的 cookie,把为它赋值 "alex porter",我们也规定了此 cookie 在一小时后过期.

最简单的cookie创建方法:

  1. <?php
  2. echo( "cookie created? : " . setcookie("cookie_name", "cookie_data" ) );
  3. ?>

实例二:cookies存数组

  1. <?
  2. setcookie("php[uid]", "1111111111111111", time()+3600);
  3. setcookie("php[color]", "black", time()+3600);
  4. setcookie("php[preference]", "english", time()+3600);
  5. if (isset ($php)) {
  6. while (list ($name, $value) = each ($php)) {
  7. echo "$name = $value<br>n";
  8. }
  9. }
  10. ?>

cookie删除:

  1. <?php
  2. setcookie ( "cookie_user", "test", time () + 60 * 60 * 24 * 30 );
  3. setcookie ( "cookie_pass", md5 ( "test" ), time () + 60 * 60 * 24 * 30 );
  4. function logout() {
  5. setcookie ( "cookie_user", "", time () + 60 * 60 * 24 * 30 );
  6. setcookie ( "cookie_pass", "", time () + 60 * 60 * 24 * 30 );
  7. }
  8. logout ();
  9. echo $_cookie ['cookie_user'] . "<br />";
  10. echo "you have successfully logged out.";
  11. ?>

下面一个利用cookies记录用户名自动登录函数实例:

  1. <?php
  2. $globals['username'] = "test";
  3. $globals['password'] = "test";
  4. function validatelogin ($username, $password){
  5. if (strcmp ($username, $globals['username']) == 0 && strcmp ($password, $globals['password']) == 0){
  6. setcookie ("cookie_user", $username, time()+60*60*24*30);
  7. setcookie ("cookie_pass", md5 ($password), time()+60*60*24*30);
  8. return true;
  9. } else {
  10. return false;
  11. }
  12. }
  13. if (validatelogin ("test","test")){
  14. echo "successfully logged in.";
  15. } else {
  16. echo "sorry, invalid login.";
  17. }
  18. ?>