tags:

views:

59

answers:

5

Thought this was super easy, but I've spent the last half hour trying to figure it out to no avail.

$unique_id = uniqid(microtime(),1);

if (is_null($_COOKIE['client_id']))
  {
  setcookie("client_id", $unique_id);
  }

But when I go to check the cookie through $_COOKIE['client_id'], I get a null value. Any ideas whats going on?

+5  A: 

Cookies have to be set before ANYTHING is outputted. also I've had many problems with cookies before.

Also, see http://stackoverflow.com/questions/2444635/cant-set-cookies-in-php/2444671#2444671 for explanation why you cant check its existence at the same time as setting it.

FallingBullets
A: 

Yeah FallingBullets has right. Be affraid when you use UTF8 file encoding - the first chars with is sent to client is UTF8 file head ( 0xEF 0xBB 0xBF). In this case is ob-start http://php.net/manual/en/function.ob-start.php not work (UTF8 file head is sent before ob-start).

What I describe is probably characteristic of the web server. Try save jour script in ascii encoding.

Aik
+1  A: 

The _COOKIE array is created when the script initializes, and is then left alone by PHP. Setting a cookie within the script will not magically add it to $_COOKIE. It will only show up on the next script request, or you manually assign it into $_COOKIE.

Marc B
A: 

You should set cookie with

$_COOKIE['key'] = 'value';
VOX
A: 

Tip:

If you are doing a redirect on the same request as setting a cookie, you must call header("Location: yourdomain.com") BEFORE calling setcookie(). If not, you are in trouble.


Correct:

header("Location: mydomain.com");
setcookie("name","myvalue");

Incorrect:

setcookie("name","myvalue");
header("Location: mydomain.com");

See the manual for more details, specially the comments.

PHP_Jedi