PHP — Check if cookie was set with secure flag
hopefully this is a straight forward question. We are moving a site from http to https, the http site has some cookies set that allows a device access to certain areas. I have reworked the code to set the cookie with the secure flag so that it must be returned over HTTPS. We have a couple of devices out and about that we can physically access but I need to change the cookie on them. is there a way to check if a cookie has the secure flag set in php. I am hoping to retrieve the cookie check if the flag is set and if not, regenerate the cookie with the secure flag set. is there a way to do that?
Hey thanks but I dont think that answers my questions, I am wanting to know how to check if a secure cookie is set.
1 Answer 1
SET Secure Cookie: To set secure flag as in this post and PHP reference.
//php code to create secure cookie. bool setcookie ( string $name [, string $value = "" [, int $expire = 0 [, string $path = "" [, string $domain = "" [, bool $secure = false [, bool $httponly = false ]]]]]] )
You are after bool secure = true & httponly=false
Read if Cookie is secure:
and to check if its secure. refer to this post
Description
array session_get_cookie_params ( void ) Gets the session cookie parameters.
Return Values
Returns an array with the current session cookie information, the array contains the following items:
«lifetime» — The lifetime of the cookie in seconds. «path» — The path
where information is stored. «domain» — The domain of the cookie.
«secure» — The cookie should only be sent over secure connections.
«httponly» — The cookie can only be accessed through the HTTP protocol.
//php code to check if its secure $CookieInfo = session_get_cookie_params(); var_dump($CookieInfo); echo $CookieInfo['secure'];
This is also a useful post from other stack if you are after a single cookie.
Detecting if the cookies are enabled with PHP
For my current project I need a detection if the cookies are enabled or not in the user’s browser.
The easiest way to do this is by using this code:
setcookie ( ‘test’ , 1 , time ( ) + 3600 ) ;
if ( ! isset ( $_GET [ ‘cookies’ ] ) ) {
header ( ‘Location:/info.php?cookies=true’ ) ;
}
if ( count ( $_COOKIE ) > 0 ) {
echo «Cookies are yummy!» ;
} else {
echo «You didn’t bring any cookies here. We are hungry!» ;
}
?>?php>
The CakePHP way is almost similar:
$this -> Cookie -> write ( ‘test’ , 1 ) ;
if ( ! isset ( $_GET [ ‘cookies’ ] ) ) {
header ( ‘Location:/info.php?cookies=true’ ) ;
}
if ( count ( $_COOKIE ) > 0 ) {
echo «Cookies are yummy!» ;
} else {
echo «You didn’t bring any cookies here. We are hungry!» ;
}
?>?php>
Ok, it’s not rocket science, but it helps 🙂
13 thoughts on “ Detecting if the cookies are enabled with PHP ”
- Daniel HofstetterJanuary 17, 2010 at 12:05 pm Hm, are you sure this works? From the setcookie documentation: “Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires.”
How to Check is Browser Cookie enabled or disabled using PHP?
As we know HTTP is a stateless protocol. In web during Client Server communication to identify a particular user it is required to maintain state. In this cause there are several state management techniques. State management techniques are available for both the side client & server. Cookie is a client side state management technique.
A Cookie is a simple text file. It can store maximum 4MB data. Due to cookies are resides in client machine in text format storing data in a cookie is not secured. Cookies are two types session cookies & persistent cookies. Session cookies are available for only that time user is interacting. Once the user close the instance of browser session cookies get destroyed. Where persistent cookies having an expiry time. During we create a cookie we have to set the expiry time for persistent cookies. Expiry time can be a day, month or a year too. Cookies are generally used for websites that have huge databases, having signup & login, have customization themes other advanced features.
Before create a cookie using any programming language we need to check first is Cookies enabled in the client browser or not. Programmatically to check this here I wrote a small php script. Which will tell you is in your machine cookies are enabled or disabled.
The logic I implemented in below script is so simple. Using setcookie() method in php I am creating a cookie with the name demo-cookie. Later using php count() function I am counting the number of cookies available in your machine. If it is greater then 0 then my cookie demo-cookie is created successfully. It means in your browser cookies are enabled. In reverse case if count is not grater then 0 then in your browser cookies are disabled. To enable cookies in your browser go to the browser setting.
is-Cookie-enabled.php
Проверьте, включены ли куки
Основываясь на связанных статьях, я придумал свой собственный подход и подумал, что хочу поделиться, кто-то другой сможет его использовать, может быть, я получу несколько критических замечаний. (Предположим, что ваши хранилища сеансов PHP в файле cookie с именем PHPSESSID )
Встраивание идентификатора сессии в ссылки возможно, но грязно. Это означает, что вы представляете идентификаторы сессий для поисковых систем. Это означает, что люди, которые делятся ссылками, могут войти в один сеанс.
Не могли бы вы обновить заголовок вопроса примерно так: Проверьте, включены ли файлы cookie с помощью javascript?
9 ответов
JavaScript
В JavaScript вы просто проверяете свойство cookieEnabled, которое поддерживается во всех основных браузерах. Если вы работаете со старым браузером, вы можете установить cookie и проверить, существует ли он. (заимствован из Модернизатор):
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;
PHP
В PHP он довольно «сложный», поскольку вам нужно обновить страницу или перенаправить на другой script. Здесь я буду использовать два сценария:
Было бы очень полезно, если бы вы могли расширить свой ответ, чтобы объяснить некоторые методы на других концах этих ссылок и сохранить ссылки для справки . Невыполнение этого требования ставит ответ под угрозу из-за гниения ссылок, и эти типы ссылок, как правило, внезапно исчезают. Благодарю.
Перенаправление не обязательно, см. Также мой ответ ниже. Вы можете проверить, что куки включены без «перезагрузки».
Но проверить, разрешены ли cookie с помощью isset ($ _ COOKIE [ «cookie» ]), вы должны обновить. Im делает это ths way (с сеансами на основе файлов cookie:)
session_start(); $a = session_id(); session_destroy(); session_start(); $b = session_id(); session_destroy(); if ($a == $b) echo"Cookies ON"; else echo"Cookies OFF";
Это самый простой и лучший пример на данный момент! Один комментарий: сначала проверьте, запущен ли уже сеанс, прежде чем делать это, и оставьте его включенным по окончании теста.
Это работает только после обновления! При первой загрузке всегда отображается « Cookies OFF», потому что нет способа проверить, включены ли cookie, не обмениваясь хотя бы одним запросом с браузером. Файлы cookie входят в состав информации заголовка каждого запроса, а операции с файлами cookie выполняются с помощью заголовков ответов. Там нет никакого способа обойти это.
Прозрачный, чистый и простой подход, проверка доступности файлов cookie с PHP и использование прозрачного перенаправления AJAX, поэтому не запускает перезагрузку страницы > . Он также не требует сеансов.
Клиентский код (JavaScript)
function showCookiesMessage(cookiesEnabled) < if (cookiesEnabled == 'true') alert('Cookies enabled'); else alert('Cookies disabled'); >$(document).ready(function() < var jqxhr = $.get('/cookiesEnabled.php'); jqxhr.done(showCookiesMessage); >);
(вызов JQuery AJAX может быть заменен на чистый вызов JavaScript AJAX)
Серверный код (PHP)
if (isset($_COOKIE['cookieCheck'])) < echo 'true'; >else < if (isset($_GET['reload'])) < echo 'false'; >else < setcookie('cookieCheck', '1', time() + 60); header('Location: ' . $_SERVER['PHP_SELF'] . '?reload'); exit(); >>
В первый раз вызывается script, cookie устанавливается, а script указывает браузеру перенаправлять на себя. Браузер делает это прозрачно. Перезагрузка страницы не выполняется, поскольку она выполняется в пределах области вызова AJAX.
Во второй раз, когда вызывается перенаправлением, если cookie получен, script отвечает HTTP 200 (со строкой «true» ), поэтому вызывается функция showCookiesMessage .
Если вызов script вызывается во второй раз (идентифицируется параметром «перезагрузка» ), и cookie не принимается, он отвечает HTTP 200 со строкой «false», а функция showCookiesMessage вызывается.