专注于discuz,uchome,dedecms等各类PHP程序仿站(二次开发和模板制作)。

« »
2010-12-23PHP+mysql

14,306 阅读

PHP中cookie设置函数,附多个开源程序设置函数代码

setcookie

(PHP 4, PHP 5)

Description

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace.

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobalssuch as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.

Parameters

All the arguments except the name argument are optional. You may also replace an argument with an empty string ("") in order to skip that argument. Because the expire argument is integer, it cannot be skipped with an empty string, use a zero (0) instead.

» RFC 2109 provides the normative reference on how each setcookie() parameter is interpreted.

name

The name of the cookie.

value

The value of the cookie. This value is stored on the clients computer; do not store sensitive information. Assuming the name is ‘cookiename’, this value is retrieved through $_COOKIE['cookiename']

expire

The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. In other words, you’ll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).

Note:

You may notice the expire parameter takes on a Unix timestamp, as opposed to the date format Wdy, DD-Mon-YYYY HH:MM:SS GMT, this is because PHP does this conversion internally.

path

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

The domain that the cookie is available to. To make the cookie available on all subdomains of example.com (including example.com itself) then you’d set it to ‘.example.com’. Although some browsers will accept cookies without the initial ., » RFC 2109 requires it to be included. Setting the domain to ‘www.example.com’ or ‘.www.example.com’ will make the cookie only available in the www subdomain.

secure

Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie will only be set if a secure connection exists. On the server-side, it’s on the programmer to send this kind of cookie only on secure connection (e.g. with respect to $_SERVER["HTTPS"]).

httponly

When TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won’t be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers). Added in PHP 5.2.0. TRUE or FALSE

上面是PHP官方最新手册上的,下面翻译的没有用第7个参数httponly,这个参数是在5.2.0时加入的,如果版本大于5.2.0时可以加入,请下面的红色代码!

PHP setcookie() 函数

定义和用法

setcookie() 函数向客户端发送一个 HTTP cookie。

cookie 是由服务器发送到浏览器的变量。cookie 通常是服务器嵌入到用户计算机中的小文本文件。每当计算机通过浏览器请求一个页面,就会发送这个 cookie。

cookie 的名称指定为相同名称的变量。例如,如果被发送的 cookie 名为 "name",会自动创建名为 $user 的变量,包含 cookie 的值。

必须在任何其他输出发送前对 cookie 进行赋值。

如果成功,则该函数返回 true,否则返回 false。

语法

setcookie(name,value,expire,path,domain,secure)
参数 描述
name 必需。规定 cookie 的名称。
value 必需。规定 cookie 的值。
expire 可选。规定 cookie 的有效期。
path 可选。规定 cookie 的服务器路径。
domain 可选。规定 cookie 的域名。
secure 可选。规定是否通过安全的 HTTPS 连接来传输 cookie。
httponly 可选。TRUE or FALSE,可以减少XSS攻击。

phpwind的cookie函数:

/**

* 设置cookie

*

* @global string $db_ckpath

* @global string $db_ckdomain

* @global int $timestamp

* @global array $pwServer

* @param string $cookieName cookie名

* @param string $cookieValue cookie值

* @param int|string $expireTime cookie过期时间,为F表示1年后过期

* @param bool $needPrefix cookie名是否加前缀

* @return bool 是否设置成功

*/

function Cookie($cookieName, $cookieValue, $expireTime = ‘F’, $needPrefix = true) {

    global $db_ckpath, $db_ckdomain, $timestamp, $pwServer;

    static $sIsSecure = null;

    if ($sIsSecure === null) {

        if (!$pwServer['REQUEST_URI'] || ($parsed = @parse_url($pwServer['REQUEST_URI'])) === false) {

            $parsed = array();

        }

        if ($parsed['scheme'] == ‘https’ || (empty($parsed['scheme']) && ($pwServer['HTTP_SCHEME'] == ‘https’ || $pwServer['HTTPS'] && strtolower($pwServer['HTTPS']) != ‘off’))) {

            $sIsSecure = true;

        } else {

            $sIsSecure = false;

        }

    }

    if (P_W != ‘admincp’) {

        $cookiePath = !$db_ckpath ? ‘/’ : $db_ckpath;

        $cookieDomain = $db_ckdomain;

    } else {

        $cookiePath = ‘/’;

        $cookieDomain = ”;

    }

    $isHttponly = false;

    if ($cookieName == ‘AdminUser’ || $cookieName == ‘winduser’) {

        $agent = strtolower($pwServer['HTTP_USER_AGENT']);

        if (!($agent && preg_match(‘/msie ([0-9]\.[0-9]{1,2})/i’, $agent) && strstr($agent, ‘mac’))) {

            $isHttponly = true;

        }

    }

    $cookieValue = str_replace("=", ”, $cookieValue);

    strlen($cookieValue) > 512 && $cookieValue = substr($cookieValue, 0, 512);

    $needPrefix && $cookieName = CookiePre() . ‘_’ . $cookieName;

    if ($expireTime == ‘F’) {

        $expireTime = $timestamp + 31536000;

    } elseif ($cookieValue == ” && $expireTime == 0) {return setcookie($cookieName, ”, $timestamp – 31536000, $cookiePath, $cookieDomain, $sIsSecure);}

    if (PHP_VERSION < 5.2) {

        return setcookie($cookieName, $cookieValue, $expireTime, $cookiePath . ($isHttponly ? ‘; HttpOnly’ : ”), $cookieDomain, $sIsSecure);

    } else {

        return setcookie($cookieName, $cookieValue, $expireTime, $cookiePath, $cookieDomain, $sIsSecure, $isHttponly);

    }

}

discuz x1.5下的Cookie函数:

function dsetcookie($var, $value = ”, $life = 0, $prefix = 1, $httponly = false) {

    global $_G;

    $config = $_G['config']['cookie'];

    $_G['cookie'][$var] = $value;

    $var = ($prefix ? $config['cookiepre'] : ”).$var;

    $_COOKIE[$var] = $var;

    if($value == ” || $life < 0) {

        $value = ”;

        $life = -1;

    }

    $life = $life > 0 ? getglobal(‘timestamp’) + $life : ($life < 0 ? getglobal(‘timestamp’) – 31536000 : 0);

    $path = $httponly && PHP_VERSION < ’5.2.0′ ? $config['cookiepath'].’; HttpOnly’ : $config['cookiepath'];

    $secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;

    if(PHP_VERSION < ’5.2.0′) {

        setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure);

    } else {

        setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure, $httponly);

    }

}

PHPCMS的Cookie设置函数:

function set_cookie($var, $value = ”, $time = 0)

{

    $time = $time > 0 ? $time : ($value == ” ? PHP_TIME – 3600 : 0);

    $s = $_SERVER['SERVER_PORT'] == ’443′ ? 1 : 0;

    $var = COOKIE_PRE.$var;

    $_COOKIE[$var] = $value;

    if(is_array($value))

    {

        foreach($value as $k=>$v)

        {

            setcookie($var.’['.$k.']‘, $v, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);

        }

    }

    else

    {

        setcookie($var, $value, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);

    }

}

DEDECMS的Cookie设置函数:

function PutCookie($key,$value,$kptime=0,$pa="/")

{

    global $cfg_cookie_encode;

    setcookie($key,$value,time()+$kptime,$pa);

    setcookie($key.’__ckMd5′,substr(md5($cfg_cookie_encode.$value),0,16),time()+$kptime,$pa);

}

WarePress的直接是默认的setcookie函数!

原创文章如转载,请注明:转载自火跃工作室
本文网址:http://www.huoyue.org/php_setcookie

日志信息 »

该日志于2010-12-23 11:33由 火跃 发表在PHP+mysql分类下, 你可以发表评论。除了可以将这个日志以保留源地址及作者的情况下引用到你的网站或博客,还可以通过RSS 2.0订阅这个日志的所有评论。

相关日志 »

  • 暂无相关日志

没有评论

发表评论 »