php之函数setcookie

WBOY
Release: 2016-06-23 14:30:35
Original
1018 people have browsed it

setcookie可以设置cookie, 不过在php设置的cookie页面第一次不能获得, 必须刷新一下,第二次才能获得.

这是因为cookie的原理:

$_COOKIE数组是从客户端返回的变量cookie值, 所以页面第一次执行时, 客户端的cookie值还没有

刷新后第二次执行已经有服务器传递的值了,所以可以获取到.

 

有一种变通的方法, 可以使得cookie值不需要刷新第一次就能生效, 其实就是给$_COOKIE数组赋值. 代码如下:

<?php    function newcookie($var, $value='', $time=0, $path='', $domain=''){    $_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);    }}// var_dump($_COOKIE);?>
Copy after login

 

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template