4

I'm developing a website on my localhost which uses cookies. I have a function that generates a random, 25 character string which will be stored in a database and set as a referential cookie on the user's browser.

I've searched the internet and this site, but wasn't able to find a solution for my problem.

Below an overview of the related code


function generateRandomString($length){
    $string = "";
    $possible = "012346789abcdefghijklmnopqrstuvwABCDEFGHIJKLMNOPQRSTUVW";
    $maxlength = strlen($possible);
    if($length > $maxlength){
        $length = $maxlength;
    }
    $i = 0; 
    while($i < $length){ 
        $char = substr($possible, mt_rand(0, $maxlength-1), 1);
        if(!strstr($string, $char)){ 
            $string .= $char;
            $i++;
        }
    }
    return $string;
}

$uCookie = generateRandomString(25);

setcookie('uHash', $uCookie, time()+60*60*24*30);

$stmt = $dbh->prepare('
    UPDATE User 
    SET u_UserCookie = :cookie 
    WHERE u_UserId = :id
'); 

$stmt->execute(array(
    ':cookie' => $uCookie,
    ':id' => $user_id
));

Now when i try echo($_COOKIE['uHash']); i get an empty string.

The strange part is that when i check my chrome preferences, the cookie does exists

Name:    uHash
Content:    134uHnEPrCmBNGqeAjhRSUiJL
Domain: localhost
Path:   /~path/to/login
Send for:   Any kind of connection
Accessible to script:   Yes
Created:    Wednesday, April 17, 2013 4:21:27 PM
Expires:    Friday, May 17, 2013 4:21:27 PM

The string '134uHnEPrCmBNGqeAjhRSUiJL' can also be found in the database, so that works

Am i missing some basic info about cookies (on a localhost)?

SOLVED

The problem is, according to php.net

'that domain names must contain at least two dots (.), hence 'localhost' is invalid and the browser will refuse to set the cookie'

So i solved it by doing this


$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
setcookie('uHash', $uCookie, time()+60*60*24*30, '/', $domain, false);
4

3 回答 3

2

See this issue: Cookies on localhost with explicit domain

Domain names in a cookie must contain two dots. Localhost therefor is invalid.

于 2013-04-18T07:05:01.640 回答
0

Be sure that you're trying to access the cookie in the right path/domain :

 setcookie ('uHash', $uCookie, time()+60*60*24*30, /path/of/the/website, false);

You need to redirect to having the headers sending your cookie before you can catch it.

See setcookie doc.

于 2013-04-18T07:05:30.297 回答
0

We don't have all the relevant code but I guess it looks like this:

setcookie('uHash', $uCookie, time()+60*60*24*30);
echo $_COOKIE['uHash'];

From the manual:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

If you absolutely need it on the same page, you can probably do this:

setcookie('uHash', $uCookie, time()+60*60*24*30);
$_COOKIE['uHash'] = $uCookie;
echo $_COOKIE['uHash'];
于 2013-04-18T07:08:35.040 回答