Cookies across sub-domains - javascript

I have two subdomains foo.example.com and bar.example.com, I am setting javascript cookies on the foo.example.com, but not able access it on bar.example.com, please suggest a way to access the cookie created on the foo.example.com on bar.example.com

In php I set a persistent cookie to do something similar, if it can be accessed from separate browsing sessions it can be accessed cross-domain i'd imagine.
I have "borrowed" this javascript from #pete because I'm not a JS expert, and barely even a novice, but I think something along these lines could work, set a cookie to expire after a year or other time period, as opposed to when browser session closes or the page has been left.
You'll need to do some messing about with it but hey, that's the fun part!
// Build the expiration date string:
var expiration_date = new Date();
var cookie_string = '';
expiration_date.setFullYear(expiration_date.getFullYear() + 1);
// Build the set-cookie string:
cookie_string = "test_cookies=true; path=/; expires=" +
expiration_date.toUTCString();
// Create or update the cookie:
document.cookie = cookie_string;

Related

Clearing a cookie via JS and yet PHP still detects it

I'm setting a "SESSION" cookie via JS:
var d = new Date();
d.setTime(d.getTime() + (2*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cookie.name + "=" + cookie.value +";"+ expires + ";
path="+cookie.path+";domain="+data.shared_domain+";";
Then I'm deleting the cookie by making it expire, via JS:
document.cookie = "SESSION=; expires=Thu, 01 Jan 1971 00:00:01 UTC; path=/;domain="+domain;
After doing this, console.log(document.cookie) will return all other cookies except this one, which is what I would expect.
On the other hand, I am doing session checks via PHP, trying to read the cookie by doing $_COOKIE["SESSION"].
isset($_COOKIE["SESSION"]) will return true, and I can read the old value of the cookie. No matter how many times I refresh the page, it still reads it.
Am I misunderstanding how cookies work? Is there another way to check if a cookie has expired in PHP?
Update:
Yes, the problem is that the cookie has an HttpOnly flag.
So now I'm trying to delete it via PHP. Based on this other question, I do:
setcookie("SESSION", "", time()-3600);
if (isset($_COOKIE['SESSION'])) unset($_COOKIE['SESSION']);
When I'm done, I check that it's gone with a quick var_dump($_COOKIE), and yes, it is nowhere to be seen.
Except that Chrome still sees it (expired in 1969), and when I navigate to another part of the site, checking for that cookie will return a value.
I will add one extra piece of information, in case it makes a difference: This cookie is shared by sub.domain.com and app.sub.domain.com. When I set it, I set it for .domain.com. And I unset it for .domain.com as well.
How can I get rid of that cookie for good?
It's not clear how you're creating the cookie in the first place; I assume using PHP's session handler, but you haven't specified.
Either way, it is likely being generated with cookie security settings that limit access to it from the JavaScript. This setting is called httpOnly and is typically used on session cookies and other similar cookie data that is intended for use only by the server-side code.
If this cookie setting has been set (and any good session handler will have set it), then you simply won't be able to set or unset this cookie from the browser; you will have to do it from your PHP code.
For more info on this topic, see this wikipedia article: https://en.wikipedia.org/wiki/Secure_cookie

PHP: Reading a cookie set with Javascript

Using Javascript & Jquery, I'm creating a cookie on a click event, and then redirecting the user to another page. I'm doing that like this:
<script type="text/javascript">
$(".my-div").click(function() {
document.cookie ="answers=:" + myAnswers + "; path=/; domain=.mydomain.com;";
setTimeout("location.href = '/my-destination-page.php/';", 5000);
});
</script>
When I reach my-destination-page.php, I can see the cookie is set correctly in Google Developer Tools. However, PHP doesn't detect that it's set:
<?php
var_dump($_COOKIE['answers']);
?>
The above returns a big fat NULL.
Any ideas why this is happening?
try to change,
document.cookie ="answers=:" + myAnswers + "; path=/; domain=.mydomain.com;";
to
document.cookie ="answers=:" + myAnswers + "; expires=Thu, 12 Aug 2015 20:47:11 UTC;path=/; domain=.mydomain.com;";
and check
I didn't test your specific code -- but I know building raw cookie strings manually is a finicky, error prone thing. If you get something wrong the cookie processing code on the server (won't recognize your cookies).
Since you're already using jQuery, I'd try using the jQuery cookie plugin. Even if you don't want to deploy with this plugin, you can use it to set your cookie, examine the request headers, and determine where your cookie string is incorrect (or determine that your cookie strings is correct, and that your problem lies elsewhere)

JavaScript can't delete/modify cookie created using Scala

I've created a cookie in Scala, which I would like Javascript to be able to delete and/or modify.
Here is how I created the cookie in Scala ensuring the httpOnly param is set to false: (
Sticky Cookies in Scala
)
I used the following method to delete the cookie in JavaScript, but the cookie does not delete.
( javascript - delete cookie )
Aside from attempting to delete the cookie, it doesn't seem like I can modify the contents of the cookie either.
How can I ensure the JavaScript can modify and delete the cookie created in Scala?
I fixed the issue.
I had to ensure that both the cookie created in Scala and the one deleted/modified in JavaScript both had the same path.
For example, in Scala:
new Cookie(sCookieID, sValue, Option(nSecondsExpire), "/", scala.None, false, false)
In JavaScript:
document.cookie = sCookieID + "=" + sValue+ "; " + sExpire + "; path=/";
Notice the path in both examples used "/". Once I used the same path, I was able to delete/modify the cookies in JavaScript. Before this I hadn't explicitly set the path in the JavaScript code.

Removing (unset) all cookies that are older that were created before today & making a subdirectory keep in browser history?

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

Some cookies not sent to server

I am attempting to set a cookie on a particular page to be read on another page. I wish to know why the other page is not being sent the cookie. Examining what is going on shows that the cookie is being set, but is not being sent to the server. My understanding was that if the path of a cookie is not set, the cookie will be sent to any page on the domain, though I tried adding path=/ to the cookie in case that would help anyhow. Opera has the cookie tagged as "Only sent to creator" for whatever reason. I'm sure I'm missing something simple.
<script type="text/javascript">
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : "; expires="+exdate.toGMTString());
}
setCookie("mycookie",document.location.href,7);
</script>
http://www.site.com/Folder/subfolder/page.aspx - Cookie set here
http://www.site.com/folder/page.aspx - Cookie should be sent here. Why isn't it?
As you said yourself, add the path:
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : "; expires="+exdate.toGMTString()+" ;path=/");
If it's not working, clear all cookies and start again. Old cookies without the path set might be messing something up.
It certainly won't work without explicitly setting path; it certainly should work if you are setting the path.

Categories