Yii 2 Not Reading a Cookie Set From Javascript - javascript

Is there a way to get the value of a cookie set by Javascript inside the Yii 2 framework?
Using this code
if(Yii::$app->getRequest()->getCookies()->has('HELLO'))
{
die("YES COOKIE");
}
else
{
die("NO COOKIE");
}
And I am seeing the HELLO cookie has been set when I inspect. However, the code is returning NO COOKIE.
The cookie was set with Javascript like so
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

cookies you set in javascript won't pass yii validation when you attempt to access them.
the whole purpose of the validation is to ensure that cookies that yii reads and writes are not tampered with.
i dont know your exact use case, but if you need a client action to set cookie data, i'd prefer to set it via an ajax request.
if it's not something sensitive (like getting a tab state or smth), use the $_COOKIE global to access it.
or, the nuclear option, disable cookie validation altogether in application config
docs could help you out here

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

Cookies across sub-domains

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;

Using Google Analytics Tracker Client ID (cid)

I'm planning to use Google Analytics Measurement Protocol. I'm currently planning to capture the Client ID (cid) by including it as a URL parameter on some Ajax requests.
I've found that I can expose the Client ID value like this:
var ga_cid;
ga(function(tracker) {
ga_cid = tracker.get('clientId');
});
I'm concerned that this route is poor form as it's polluting the global namespace. However, I've been unable to unearth a more elegant (best practice) solution.
What is the "right" way? Am I overthinking this?
Yes you may be right on this. Its instead better not to get the Client ID from the Cookie as the official documentation recommends. You can do something like below:
ga(function(tracker) {
var clientId = tracker.get('clientId');
});
There are more options mentioned on this page on how to retrieve it based on how your page is setup.
I ended up making a cookie and referencing it from PHP instead of a global JavaScript variable that I'd have to pass when making AJAX calls.
// put the Google Analytics Client ID into a cookie, so that it will be available to PHP
ga(function(tracker) {
var date = new Date();
date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
document.cookie = 'ga_cid=' + tracker.get('clientId') + '; expires=' + date.toUTCString() + '; path=/';
});
Then in PHP:
$ga_cid = filter_input(INPUT_COOKIE, 'ga_cid');

How to get cookie's path using javascript

My set Cookie js function
function setCookie(name, value, expires, path){
cookieStr = name + "=" + escape(value) + "; ";
if(expires){
expires = setExpiration(expires);
cookieStr += "expires=" + expires + "; ";
}
if(path){
cookieStr += "path=" + path + "; ";
}
document.cookie = cookieStr;
}
When I create a cookie,
setCookie('MyCookie','cookieName',3,'/Members')
How to get cookie's path?
TL:DR;
You cannot read through cookies based on path using javascript.
In JavaScript, you can only set or get cookies by using the internal object document.cookie. And the content of this object will be a string of key value pairs of non-httpOnly cookie names and values separated by a ;. And that is pretty much it.
There is no way you could get a trace of Path, Domain and other attributes of cookies as they are only read by browsers and not shown to JavaScript.
On the other hand, If you are using any form of AJAX, You could try to intercept and parse the request headers by xhr.getResponseHeader("Set-Cookie") and store the value in localStorage or sessionStorage as per your need. I still advise you that it is not a good idea. Some of the browsers might consider Set-Cookie header as one of the forbidden headers to be read by javascript. but I think that restriction is only for httpOnly cookies.

onSubmit function sends cookie even without submit

I simply try to set cookie when form is submitted but it seems that the function sets
cookie on every refresh of page
function Sub(){
var exdays="3000";
var value="asdf";
var exdate=new Date();
var c_name="asdf";
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
alert("asdf"); //just for debugging
return true; }
</SCRIPT>
<form id="myform" action="http://localhost" onsubmit="return Sub();">
The cookie will be sent by the browser on each request for the same URL until it is deleted, it expires, or for session cookies, until a new session is created.
You're setting an expiration, so it's not a session cookie. So your browser will send the cookie on each page load to that URL, regardless of whether you clicked something or not.
Try removing the expiration date, clearing your cookie cache, and restarting your browser.
The cookie will not be present until you submit once. Then the cookie will be present until you close your session (restart the browser).
Do you mean the cookie is changed on every reload or that the cookie exists?
I am assuming here that you are using the cookie to send a bit of information to the server along with the form.
Cookies are persistent, and will stick around until they are changed. It might make more sense to have a hidden field in the form, and change the value of that, instead of setting a cookie.

Categories