PHP: Reading a cookie set with Javascript - 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)

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;

Removing sign in cookies on sign out

I'm having trouble with cookies and getting some weird behavior. For now the cookie are set on sign in like so:
document.cookie = "cookie1=" + cookie1 + "; expires=0; path=/";
document.cookie = "basicAuth=" + basicAuth + "; expires=0; path=/";
document.cookie = "cookie2=" + cookie2 + "; expires=0; path=/"
That works fine. I have a sign out button in the header and on click it does the following:
document.cookie = "cookie1=";
document.cookie = "basicAuth=";
document.cookie = "cookie2=";
In the header script I have a simple check to see if cookie1 is empty and to hide the header nav bar and redirect to sign in if it is:
if (getCookie("cookie1") == "") {
$(".navbar").css({"display":"none"});
window.location.href = "/signin";
}
Right now I am able to log out effectively the first time, but logging back in and logging out again seems not to work properly. I still see the navbar and the redirect seems to only work selectively. Is there a better way to set or delete cookies?
When you delete a cookie, you should also add the date and path, and the date should be in the past to remove the cookie, so something like
document.cookie = "cookie1=; expires=Thu, 01 Jan 1970 00:00:01 GMT;";
The specification says
...to remove a cookie, the server returns a Set-Cookie header with an
expiration date in the past. The server will be successful in
removing the cookie only if the Path and the Domain attribute in the
Set-Cookie header match the values used when the cookie was created.
Cookies are generally easier to work with in Javascript if you use helper functions that set the name, value, UTC timestamp etc. for you, instead of doing it every time you set or get a cookie.
What you're doing just sets the cookie to an empty string, it's never really removed.

Javascript/jquery equivalent of echoing (PHP) cookie value

I have a cookie named myName
In php, to print the cookie value, I can simply do
<?=$_COOKIE['myName']?>
The shortest I have found in JS is:
<script>
document.write($.cookie('myName'));
</script>
Is there not a better/shorter way to do this? Maybe with JQuery?
I am quite new to JS and moving a site over from PHP for mobile Phonegap Build dev so can't use PHP
If you don't want to use a plugin like jQuery $.cookie, you can do something like this
function getCookie(cookiename) {
var cookiestring = RegExp(""+cookiename+"[^;]+").exec(document.cookie);
return unescape(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");
}
var value = getCookie('myName');
FIDDLE
You can use jQuery Cookie plugin (http://plugins.jquery.com/cookie/) and get cookie just like
$.cookie("myName")
And what you will find very usefull is to use the console while debugging: write in your code:
console.log(document.cookie);
or
console.log($.cookie('myName'));
And see the results in the javascript console of your browser (easiest way: right click in your page, go to the last item which says "inspect element", and in the window that will open, go to the last tab, named "console".)
use a self executing function
<script>
(function(){document.cookie="username=test; expires=Fri, 28 Feb 2014 12:00:00 GMT; path=/";})();
</script>
check out more information on MDN

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