开发者

PHP: Cookie problem

Can anyone tell me what is wrong with my code?

<?php
开发者_StackOverflow中文版class MyCookie
{
    private $expiration = 0;
    private $path = "";
    private $domain = "";
    private $secure = false;
    private $httponly = false;
    private $names = array();

    public function __construct($e, $p = "/temp/", $s = false, $h = false) {
        $this->expiration = $e;
        $this->path = $p;
        $this->domain = '.' . $_SERVER["SERVER_NAME"];
        $this->secure = $s;
        $this->httponly = $h;
    }

    public function getDomain() {
        return $this->domain;
    }

    public function write($name, $value) {
        return setcookie($name, $value, time() + $this->expiration, $this->path, $this->domain, $this->secure, $this->httponly);
    }

    public function delete($name) {
        return setcookie($name, $value, time() - $this->expiration, $this->path, $this->domain, $this->secure, $this->httponly);
    }

    public function read($name) {
        return $_COOKIE[$name];
    }
}

session_start();

$cookie = new MyCookie(3600 * 24 * 30);

$cookie->write('name', 'jun');

echo $cookie->read('name');

?>

Somehow the cookie is not registering or showing up.


Cookie won't show up in $_COOKIE array until you reload the page (cookies are sent with HTTP response)


Two suggestions...

a) Try making the cookie visible to your whole domain, rather than a specified path

b) Get the Web Developer Toolbar for Firefox so you can easily view the current list of Cookies while you browse, which is really useful for de-bugging.


In PHP, the cookie is not actually set until the page reloads. You're creating the cookie then immediately trying to get a value from $_COOKIE, but that value doesn't exist yet in $_COOKIE.


Although it's generally not a good idea to alter values of any of the superglobal arrays, you can do this:

replace:

public function write($name, $value) {
    return setcookie($name, $value, time() + $this->expiration, $this->path, $this->domain, $this->secure, $this->httponly);
}

with:

public function write($name, $value) {
    $_COOKIE[$name] = $value;
    return setcookie($name, $value, time() + $this->expiration, $this->path, $this->domain, $this->secure, $this->httponly);
}

setcookie will not moify the $_COOKIE superglobal.


Is your directory currently '/temp/'? If not, the cookie won't be passed along. Try not giving the new cookie a directory while you're at it, it will auto set to the correct one anyway.


Yup it isn't registering because it needs to reload the page.
It works like this:
_>Http Request
_>Php SetCookie
_>Http Response with cookie header
->New Http Request with cookie
->Php can read cookie now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜