L
L
Lici2018-08-21 16:56:34
PHP
Lici, 2018-08-21 16:56:34

How to check whether a cookie is enabled in php?

Hello, is it possible to determine at the PHP level whether the visitor has cookies enabled? If so, how?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evgeny Romashkan, 2018-08-21
@EvgeniiR

This is easier to do in javascript.
For new browsers: For old ones:if (navigator.cookieEnabled) return true;

// set and read cookie
document.cookie = "cookietest=1";
var ret = document.cookie.indexOf("cookietest=") != -1;

// delete cookie
document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";

return ret;

If in php then like this:
<?php
session_start();
setcookie('foo', 'bar', time()+3600);
header("location: check.php");

and check.php:
<?php echo (isset($_COOKIE['foo']) && $_COOKIE['foo']=='bar') ? 'enabled' : 'disabled';

A
Alexander Aksentiev, 2018-08-21
@Sanasol

In 2 requests to the server
1. set the cookie
2. check whether it exists or not
In the first request, the cookie is only sent to the client, so until the next one we do not know whether the cookie was stored on the client or not.

D
dollar, 2018-08-21
@dollar

PHP + JavaScript + Ajax
On the page that is shown to the user, JS detects the presence of cookies and sends information to the server via Ajax (in fact, this will be the second request to the server).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question