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);