设置cookie当天内有效(0 位领导批示)

经典论坛上一位朋友的问题

我的解决方法


<?php
//设置默认时区
date_default_timezone_set('Etc/GMT-8');
//得到明天0点时的unix时间戳
$nonce_time = strtotime(date('Ymd')+1);
//相减得到过期所剩的时间
$expire_time = $nonce_time - time();
//echo $expire_time;
setcookie('test', '当天有效,到7月4号就失效哦!', $expire_time);
?>

setcookie函数的作用域问题(0 位领导批示)

在不同目录下的文件.不能访问各自设置的cookie

查了一下手册.setcookie函数有一个path参数.可以设置本地cookie的作用域

解释如下:

The path on the server in which the cookie will be available on. If set to ‘/’, the cookie will be available within the entire domain . If set to ‘/foo/’, the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain . The default value is the current directory that the cookie is being set in.

另一个参数domain
则是设置网络上cookie的作用域.

解释如下:

The domain that the cookie is available. To make the cookie available on all subdomains of example.com then you’d set it to ‘.example.com’. The . is not required but makes it compatible with more browsers. Setting it to www.example.com will make the cookie only available in the www subdomain. Refer to tail matching in the » spec for details.

示例:

  1. $setcookday = 30;//设置cookie有效期
  2. setcookie('uname', '银子', time() + ($setcookday * 24 * 60 * 60),'/','qqdang.net'); //分别为cookie名称.cookie值.cookie有效时间.cookie本地作用域.cookie网络作用域

随机显示的10篇日志

评论最多的10篇日志

浏览最多的10篇日志