I'm setting my cookies like this:
document.cookie = `${cookieName}=${JSON.stringify(cookieObject)};path=/;SameSite=Strict;Secure=true;expires=${someDate.toUTCString()};`
Everything is fine at first. But when I refresh, the cookie disappears and firefox console tells me a message:
Cookie “thecookiename” will be soon rejected because it has the “SameSite” attribute set to “None” or an invalid value, without the “secure” attribute.
If I refresh again, the message disappears and the cookie is also gone.
Chrome acts the same, but minus the message.
Edit
I realized, the problem might be related to the fact, that I'm overriding the document.cookie setter.
document.setCookie = document.__lookupSetter__('cookie');
document.newCookieSetter= (cookie) => {
// here I check, whether a cookie is allowed or not. Calls for an api endpoint to get the information.
if (cookieDataRecieved() && cookieIsAllowed(cookie)) {
return document.setCookie(cookie);
}
cacheCookie(cookie); // If cookie data has loaded, try checking again.
}
document.__defineSetter__('cookie', document.newCookieSetter);
The problem applies to every cookie added through the document.cookie = "somecookie";
The Secure attribute has no value, it's just a bare attribute (present or absent), so just replace Secure=true with Secure.
Related
I just recently started trying to use the cookie library js-cookie:
Found here: https://github.com/js-cookie/js-cookie
I can't seem to determine whether my cookies are being set or read correctly. The main goal is to read if a checkbox is checked, create a cookie and use that on another page to change some elements.
Here's how I attempted setting the cookie:
$('#food').click(function() {
if ($(this).is(':checked')){
Cookies.set('food', 'true');
}
else{
Cookies.remove('food');
}
});
It properly reads the checkbox being checked on click, so I know it is at least reaching the cookie set.
For reading the cookie value:
if(Cookies.get('food') === 'true'){
$('#food').css("color", "#198a80");
}
I followed the documentation on the repository page for setting and it looks correct. I assumed reading the cookie just passed the value portion as a normal variable and it could be compared like normal, but the code just does nothing, so I guessed the problem was either with the setting or reading of the cookie.
I have a function that request a data for the user one time. I need reload the page after save these data in a cookie and server read these cookie, but i dont know if these cookie are defined or not. ¿How i reload only one time if i dont have a counter and dont like use parameter? the referrer dont change with reload.
I now have this methot, but i like change for remove parameters:
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null
}
if (getURLParameter('reload') != 'true') {
//here have function for load cookie
window.location = window.location.href + '?reload=true';
}
HTTP is a stateless protocol, which mean there is not way - within the protocol - to know the state of a request. For instance : is it the first time it's launched or the second time ?
Usual workarounds are adding a parameter to the request, as you suggests or using a cookie on the browser's side. This is how sessions are implemented in platforms like Java EE or PHP.
Why don't you test for another cookie like 'never been reloaded', if it does not exists : create this cookie and reload the page.
The tricky part is when should you delete the cookie, ie : when does your business logic wants you to reload the page again ? That's up to you to decide.
I am trying to store in a cookie the state of a certain element on my page, more precisely the expanded or shrunk state of a sidebar.
I have managed to store it properly and it works, but I've noticed that if I refresh the page and toggle the sidebar from the expanded or shrunk state, there is a second cookie added, with the same name, but a new value.
Here is what the log outputs:
expanded=false; expanded=true; PHPSESSID=2314324545
I needed the cookie so that if the user wanted to go on another page, he could see the sidebar the way he left it in the previous page. Now if I have 2 cookies with the same name, this raises a problem when I am checking its value.
Here is how I have implemented it:
$('.expand-button').on('click', function(e) {
$('.pushmenu').toggleClass('expanded');
$('.navbar-left').toggleClass('expanded');
$('.navbar-left-2').toggleClass('small')
if( $(window).width()+scrollbarWidth > 1240){
$('.container.fluid-content').toggleClass('shrinked')
}
if($('.pushmenu').hasClass('expanded')) {
expandedValue = true;
document.cookie = 'expanded=' + expandedValue;
console.log(document.cookie);
} else {
expandedValue = false;
document.cookie = 'expanded=' + expandedValue;
console.log(document.cookie);
}
})
$(window).on('load', function() {
//cookie is already set
console.log(document.cookie);
if( document.cookie.indexOf('expanded=true') != -1 ) {
$('.pushmenu').toggleClass('expanded');
$('.navbar-left').toggleClass('expanded');
$('.navbar-left-2').toggleClass('small')
if( $(window).width()+scrollbarWidth > 1240){
$('.container.fluid-content').toggleClass('shrinked')
}
} else {
console.log('not doing anything');
}
})
Cookies are linked to the path and the domain name. You may receive two (or more!) cookies on the server side if each have a different domain name such as:
.domain.org
.www.domain.org
The order in which you receive the cookies is the least qualified domain name to the most qualified domain name (as shown in that list.)
I suggest you install FireBug (assuming you are using a FireBug compatible browser such as Firefox) and have a look at the cookies in there. You will see the details such as the path and domain name and also the expiration date.
To set the path, just use something like this:
blah=value; Path=/
Similarly, you can force the domain with:
blah=value; Domain=.domain.org
You may specify multiple parameters by separating them by semi-colons:
blah=value; Path=/; Domain=.domain.org
If you are using HTTPS (secure domain), I strongly advice you use Secure too:
blah=value; Path=/; Domain=.domain.org; Secure
Using FireBug, you can delete some of the cookies. It is up to you to do that, use the first version (.domain.org) or the last (.www.domain.org).
The discrepancy may come from your front end code (JavaScript) AND your backend code (your PHP). One way to see what your server returns, to see whether the Path and Domain are both specified as expected, is to use wget with the -S command line option:
wget -S http://domain.org
wget -S http://www.domain.org
If you allow both "" and "www", then you must force the domain without the www:
; Domain=.domain.org
Otherwise you will get those duplicates.
I'm trying to remove all cookies from my website that were created before today... so that anyone who's a returning to the site will lose all of their old cookies and will get a fresh set of cookies.
I can't use RequestHeader unset Cookie because it will just keep removing cookies until I remove it, I want it so it removes all cookies made before 07/01/2015
I'm also trying to "fix" my site so that browsers remember the directory /f1fol/ because for some reason no browser remembers that page (not sure what's causing the problem)
Anyone know how to do this/what's the problem?
Here's the thing: a browser never reports the creation date of a cookie. When a cookie is created, only the expiration date the server specified during its creation is stored along with its value, and hence, only that gets reported back to the server until the day the cookie crumbles/expires.
But, the end effect which you want, that anyone who's returning to the site should lose all of their old cookies and get a fresh new set is possible to achieve. Add the following code to a PHP include file named, say, purge_old_cookies.php
<?
// Check if this script has run before
if (!isset($_COOKIE['purged_once'])) {
// Check for old cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(";", $_SERVER['HTTP_COOKIE']);
// Iterate and unset all cookies
foreach ($cookies as $cookie) {
$fields = explode("=", $cookie);
$name = trim(fields[0]);
// unset any cookie for the current path
setcookie($name, "", time() - 3600);
// unset the cookie for the root path
setcookie($name, "", time() - 3600, "/");
}
}
// Set a purged marker for the current path
setcookie("purged_once", "1", strtotime("+6 months"));
}
?>
A cookie is forced to expire by setting its expiration date in the past. The code above sets it to yesterday.
Notice, the setcookie() method is fired twice as the cookies must be deleted with the same parameters as they were set with. The above would suffice in most cases but if your site had set cookies with different domain, secure or httponly parameters, you may have to pass them as well.
Once the above script is ready, just include it at the beginning of all the required pages.
<?
include '/path/to/purge_old_cookies.php';
...
?>
If you're sure that your site never set a cookie for a specific /dir/path i.e. always passed a path value of /, then you can unset all the cookies by adding this script to just /index.php. The two setcookie() calls (with and without /) then effectively become the same and you can drop one. The purged_once cookie would also be set on root as
setcookie("purged_once", "1", strtotime("+6 months"), "/");
This would also restrict the marker cookies to just one per user.
Please Note:
Keep the marker purged_once cookie set to expire after a long time
like 3 to 6 months. If you keep it very low and forget to
remove the script, you'll end up purging all the new cookies your site
sets from the time this script was introduced.
In PHP setcookie function, you can set the time the cookie expires. If you want it to expire today, you can try something like that:
setcookie('var', 'value', strtotime(date('Y-m-d 23:59:59'));
and this will make it to expire in the last second of the current day. You can check cookie existence like that:
if (isset($_COOKIE['var'])) {
//do something with it
} else {
//store cookie var and do something else
}
If you need to store a directory path for a longer time, you can set expiry time to a far future date.
May be from PHP, you can also change the life span of a cookie from javascript as well. You can simply read the cookie and if date is less than your desired time delete the cookie .more
I have set a session in PHP, which is creating a cookie: PHPSESSID...
I can detect this in Chrome & Opera by using document.cookie. However in Forefox, document.cookie also returns cookies set on the page by other domains, e.g. Google Analytics.
In PHP I am setting the sessions like:
session_start();
$_SESSION['source'] = &$ref['source'];
$_SESSION['term'] = &$ref['term'];
session_write_close();
I need to be able to detect if this session is set in Javascript, by locating the cookie. What is the best way to go about this?
At the moment I am just using:
document.cookie.indexOf( 'PHPSESSID' )
which seems like a bit of a botch.
The document.cookie property will return all the cookies. While your indexOf will work, it will break if your cookies actual data contains 'PHPSESSID'. It will also match the following cookie 'MYPHPSESSIDIDIT', as it contains your cookie name.
You could parse the cookies with the following function (not tested):
function getCookieValue(name)
{
// find cookie entry in middle?
var s=document.cookie,
c=s.indexOf("; "+name+"=");
if(c==-1)
{
// no, is it at the start?
c=s.indexOf(name+"=");
if(c!=0) return null;
}
// get length of value
var l=c+name.length+1,
e=s.indexOf(";",l);
// is it at the end?
if(e==-1) e-s.length;
// cut out the value
return s.substring(l,e);
}
Hope this helps
Use this Jquery plugin, it's so cool.
https://github.com/carhartl/jquery-cookie
You can use it like this way:
if($.cookie('PHPSESSID') != undefined){
//PHPSESSID exists
}