php 下设置cookie问题澳门新葡亰网址大全

2019-09-30 作者:网络时代   |   浏览(138)

先看phpcms中的一个函数

在php下设置了cookie,CI下set_cookie()方式,但是发现cookie不能马上生效,需要刷新后才能获取,后来在网上找到了一个解决办法,$_COOKIE[$var] = $value;多加一句就可以实现不刷新cookie生效

 代码如下

//PHP COOKIE设置函数立即生效,支持数组
function cookie($var, $value = '', $time = 0, $path = '', $domain = '', $s = false)
{
    $_COOKIE[$var] = $value;
    if (is_array($value)) {
        foreach ($value as $k => $v) {
            setcookie($var . '[' . $k . ']', $v, $time, $path, $domain, $s);
        }
    } else {
        setcookie($var, $value, $time, $path, $domain, $s);
    }
}

phpcms/libs/classes/param.class.php
/**
     * Set Cookie
     * @param string $var
     * @param string $value
     * @param int $time
     * @param string $path
*/

    public static function set_cookie($var, $value = '', $time = 0, $path = '') {
        $time = $time > 0 ? $time : ($value == '' ? SYS_TIME - 3600 : 0);
        $s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
        $var = pc_base::load_config('system','cookie_pre').$var;
        $path = $path == '' ? pc_base::load_config('system','cookie_path') : $path;
        $_COOKIE[$var] = $value;
        if (is_array($value)) {
            foreach($value as $k=>$v) {
                setcookie($var.'['.$k.']', sys_auth($v, 'ENCODE'), $time, $path, pc_base::load_config('system','cookie_domain'), $s);
            }
        } else {
            setcookie($var, sys_auth($value, 'ENCODE'), $time, $path, pc_base::load_config('system','cookie_domain'), $s);
        }
    }
param::set_cookie('auth', '',time()-1,'/');

这个函数与cookie没什么区别我们先不介绍它,可能很多朋友懂,下面我们再看

setcookie函数的第四个参数为cookie路径,关于路径的设置,本文做了一些尝试,下面是两个测试页(直接用url表示路径和文件目录了):

  http://localhost/test/cookie/father.php

  http://localhost/test/cookie/child/child.php

 

 代码如下

<?php
//location:  locahost/test/cookie/father.php

//setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1);
setcookie("father_set_1_/","@@@@",time()+24*3600,"/");
setcookie("father_set_2_/child","@@@@",time()+24*3600,"/child/");
setcookie("father_set_3_test/cookie/child","@@@@",time()+24*3600,"/test/cookie/child/");

print_r($_COOKIE);
?>

 

 代码如下

<?php
//location:   localhost/test/cookie/child/child.php

//setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1);
setcookie("child_set_0","@@@@",time()+24*3600);
setcookie("child_set_1_/","@@@@",time()+24*3600,"/");
setcookie("child_set_2_/child","@@@@",time()+24*3600,"/child");
setcookie("child_set_3_/test/cookie/child/","@@@@",time()+24*3600,"/test/cookie/child/");

print_r($_COOKIE);
?>

分别按如下顺序访问页面father.php—>child.php—>father.php—>child.php,使用firebug查看,分别有如下结果:

澳门新葡亰网址大全 1

* 第一访问father.php*

本文由澳门新葡亰网址大全发布于网络时代,转载请注明出处:php 下设置cookie问题澳门新葡亰网址大全

关键词: