How to detect if cookie is set in Javascript ? - javascript

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
}

Related

document.cookie returns only PHPSESSID=*random number*

I'm trying to get a cookie I have set but all I'm getting is the PHPSESSID.
I set my cookie in a separate PHP page with:
setcookie("username", $sentname, time()+(60*60*24*30),NULL,NULL,NULL,false);
I can then find it through firefox settings.
When I try to access it using JavaScript on a different page I use:
<script>
$(document).ready(function(){
var cookie = document.cookie;
alert(cookie);
});
</script>
which then returns:
PHPSESSID=gvjsgfd8etlbdq43lndni3o0g4
It should return all the cookies, only "username" so far, I have set in a key paired string. I tried using the jquery plugin for cookies and it returned the same thing. I also couldn't find this problem elsewhere online.
Not sure if I should delete the question but one of the related links gave me the answer.
The cookie path must be set to '/' to be accessible from all subdomains. so I changed it too:
setcookie("username", $sentname, time()+(60*60*24*30),'/',NULL,NULL,false);
which gives me:
PHPSESSID=gvjsgfd8etlbdq43lndni3o0g4; username=asdf

Why is a cookie stored twice?

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.

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

How Can I Insert A Value With Javascript (or PHP) Into a Form Depending On Visitor Referral

I'm not sure if the way to do this is check Google Analytics cookies or otherwise track where a user came to my site from. Basically I have a form with a hidden field code="XY1" Now I need to be able to insert a different preset code for say people who came from Facebook, so the script would have to check where the visitor came from and then assign a code XF1 to any from FB, and a code XT1 to any from Twitter, etc.
Would something like this PHP work for the capture?:
$referringPage = parse_url( $_SERVER['HTTP_REFERER'] );
if ( stristr( $referringPage['host'], 'facebook.com' ) )
Or this JS
var ref = document.referrer;
if (!ref.indexOf("facebook.com") != -1) {
document.write(...)
}
I'm not sure what is the best way to do it and what kind of methods can reliably check the source of a visitor, so any help would be greatly appreciated.
You can use $_SERVER['HTTP_REFERER'], but it's not guaranteed to be accurate, or even present. Not all browsers will necessarily set it, and some allow you to set it yourself. Google cookies won't contain any site history, and you can't examine the browser history, so there's no guaranteed way to do what you're asking.
You can try this option using jquery $.test() method.
$(function(){
var referer=document.referrer, //option 1
//referer="<?php echo $_SERVER['HTTP_REFERER'];?>",//optional 2
XFB=/facebook.com/g,
XFT=/twitter.com/g,
checkF1=XFB.test(referer),
checkF2=XFT.test(referer);
if(checkF1){
var code= "XF1";
$('#hiddenInput').attr('value','ref: '+referer)
}
else if(checkF2){
var code= "XT1";
$('#hiddenInput').attr('value','ref: '+referer)
}
});

Javascript to "export" all cookies?

There is a cool Firefox extension which lets you export all cookies to a Netscape HTTP Cookies File, cookies.txt, which you can then use with wget (et.al.)
Here is an example cookies.txt file for the happycog.com site:
# Netscape HTTP Cookie File
# http://www.netscape.com/newsref/std/cookie_spec.html
# This is a generated file! Do not edit.
cognition.happycog.com FALSE / FALSE 1345696044 exp_last_visit 998800044
cognition.happycog.com FALSE / FALSE 1345696044 exp_last_activity 1314160044
How can I build the same style "cookies export" with Javascript? Granted it would only be able to read cookies for the current domain. That would be just fine.
Additional Details:
I realize that cookies can't be exported to the file system with pure javascript. I'd be happy with them being exported to a textarea, or with document.write. I just want to know how I can get them in the same format where I can basically copy and paste them to a cookies.txt file. The challenge here is to do it with javascript, though, and not to use an addon.
var cookieData = document.cookie.split(';').map(function(c) {
var i = c.indexOf('=');
return [c.substring(0, i), c.substring(i + 1)];
});
copy(JSON.stringify(JSON.stringify(cookieData)));
This will export your cookies into an array of key/value pairs (eg. [ [key1, val1], [key2, val2], ...]), and then copy it to your clipboard. It will not retain any expiration date info because that's impossible to extract via Javascript.
To import the cookies back, you'd run the following code:
var cookieData = JSON.parse(/*Paste cookie data string from clipboard*/);
cookieData.forEach(function (arr) {
document.cookie = arr[0] + '=' + arr[1];
});
Sorry about the delayed response - had to sleep. I have just been playing with this and concluded that the answer is NO.
The reason for this is that Javascript does not have access to any more information than the cookie's name and value, you can't retrieve the path, expiry time, etc etc. What do you actually want to do? Is this for one specific site you are developing or just for general use when browsing?
All cookies for the page is stored in document.cookie

Categories