Can't access existing php cookie
<p>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.</p>

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

<p>Below an overview of the related code</p>

<pre><code>
function generateRandomString($length){
    $string = "";
    $possible = "012346789abcdefghijklmnopqrstuvwABCDEFGHIJKLMNOPQRSTUVW";
    $maxlength = strlen($possible);
    if($length &gt; $maxlength){
        $length = $maxlength;
    }
    $i = 0; 
    while($i &lt; $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
));
</code></pre>

<p>Now when i try <code>echo($_COOKIE['uHash']);</code> i get an empty string.</p>

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

<pre><code>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</code></pre>

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

<p>Am i missing some basic info about cookies (on a localhost)?</p>

<p><strong>SOLVED</strong></p>

<p>The problem is, according to php.net <blockquote>'that domain names must contain at least two dots (.), hence 'localhost' is invalid and the browser will refuse to set the cookie'</blockquote></p>

<p>So i solved it by doing this</p>

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