Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

cookies

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.


1 Answers

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.

like image 84
glowworms Avatar answered Dec 06 '25 14:12

glowworms