Can't access existing php cookie -
this question has answer here:
- cookies on localhost explicit domain 13 answers
i'm developing website on localhost uses cookies. have function generates random, 25 character string stored in database , set referential cookie on user's browser.
i've searched internet , site, wasn't able find solution problem.
below overview of 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 u_userid = :id '); $stmt->execute(array( ':cookie' => $ucookie, ':id' => $user_id ));
now when try echo($_cookie['uhash']);
empty string.
the strange part when check chrome preferences, cookie exists
name: uhash content: 134uhneprcmbngqeajhrsuijl domain: localhost path: /~path/to/login send for: kind of connection accessible script: yes created: wednesday, april 17, 2013 4:21:27 pm expires: friday, may 17, 2013 4:21:27 pm
the string '134uhneprcmbngqeajhrsuijl' can found in database, works
am missing basic info cookies (on localhost)?
solved
the problem is, according php.net
'that domain names must contain @ least 2 dots (.), hence 'localhost' invalid , browser refuse set cookie'
so solved doing this
$domain = ($_server['http_host'] != 'localhost') ? $_server['http_host'] : false; setcookie('uhash', $ucookie, time()+60*60*24*30, '/', $domain, false);
see issue: cookies on localhost explicit domain
domain names in cookie must contain 2 dots. localhost therefor invalid.
Comments
Post a Comment