the_nutria
the_nutria

Reputation: 75

test if a cookie has been set, php

I need to run a query only if a cookie wasn't set and it has just been set. (in other words, it is the first time the user visits the page)

I tried the following:

$cookiename = "item_".$itemid;

if(!isset($_COOKIE[$cookiename])){
    setcookie($cookiename, "viewed", time()+60*60*18);
    $was_set="no";
}

//if it wasn't set and now it is
if(isset($_COOKIE[$cookiename]) and $was_set=="no") {
    mysql_query("UPDATE items_details SET views=views+1 where iid=$itemid");
    echo "<!-- +1 view -->";
}
else {
    echo "<!-- +0 views -->";
}

the first part works well, the cookie is set if it wasn't, but the second part doesn't works, it always returns the +0 views

the isset($_COOKIE[$cookiename]) expression always returns false, even if the cookie was set just 6 rows above.

Upvotes: 1

Views: 963

Answers (2)

Vineet1982
Vineet1982

Reputation: 7918

setcookie only sets up the header, that is being sent to the client. It doesn't change the $_COOKIE superglobal. In other hand - $_COOKIE is filled up with the cookies sent from the client. So at first step - you set the cookie with setcookie and have nothing in $_COOKIE because client hasn't sent it yet, and will only on the next request. So it is normal that the cookie is not immediately available in the _COOKIE superglobal.

Upvotes: 0

AndrewR
AndrewR

Reputation: 6758

setcookie() adds the Set-Cookie: header on the response.

$_COOKIE contains the cookies the browser sends on the request.

When you use setcookie() it does not effect $_COOKIE immediately, however the next time you load the page, $_COOKIE will have your value because the browser has sent the cookie data in the request.

You'll need to refactor your code a bit so you aren't checking for a value in $_COOKIE after using setcookie in the same request.

Upvotes: 2

Related Questions