tags:

views:

77

answers:

6

Can anyone tell me what is wrong with my code?

<?php
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.

+2  A: 

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.

Sohnee
yeah, I did changed the path to the root directory. thanks
jun
+3  A: 

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

Silver Light
Hmm.. So I keep on overwriting the same index over again.
jun
+2  A: 

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.

wmid
A: 

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.

Mike Sherov
A: 

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.

henasraf
A: 

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.

DCC