Is it possible to check if cookies are allowed in php without reloading the page?

For example, code such as the following does not 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";
}

I am trying to write an accurate "unique user" counter on my site, which works on the basis of checking if the user has a cookie installed on the computer, if they do not, he does +1 and sets the cookie. The problem is that users without cookies will only +1 on each page load, so naturally, I only want to run this code for those who have cookies.

However, the cookie checker above always returns $ cookies = "foobar" when the first page loads, regardless of who has cookies or not. Therefore, if the user simply views 1 page of the site, their visit will not be registered by the counter.

+3
source share
2 answers

You cannot immediately check the availability of cookies by checking the set value, since cookies are not sent to the browser until the next round trip to the client.

One thing you can do is set a cookie on the page and then check it on the script image.

There are other workarounds.

+1
source

, , javascriptcheck , ajax . PHP , cookie , , , .

0

Source: https://habr.com/ru/post/1784662/


All Articles