开发者

Is it possible to check if user has cookies enabled in php without a page reload?

For example, code such as the following doesn't seem to work, even if the cookie is actually set, until I refresh the page.

setcookie("cookies","1", time()+ 86400,"/" ); 
if (!isset($_COOKIE["cookies"])) {  
   $cookies = "foobar";
}

Im trying to write an accurate "unique user" counter on my site, which works based on checking to see if a user has a cookie set on the computer, if they don't, it does +1, and sets the cookie. The problem here is that, the users without cookies will just +1 on every page load, so naturally I only want to run this code for those who have cookies enabled.

The cookie checker above however will always return $cookies = "foobar" on the first page load, regardless of users having cookies on, or off开发者_开发问答. So if a user just views 1 page of the site, their visit won't be registered by the counter.


You cannot immediately check for its existence of cookies by checking the set value, because cookies are not sent to the browser until the next round trip to the client.

One thing you could do is set the cookie on the page, and then check it on an image script.

There are other workarounds.


The idea that comes to my mind is doing a javascriptcheck after the page is loaded, then using ajax to write the counter to the database or whereever you wish to store it. PHP is serverside while the cookie is stored clientside so doing the check like you're trying to is going to be a problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜