Closed Thread Icon

Preserved Topic: Best examples of 'cookie' coding (Page 1 of 1) Pages that link to <a href="https://ozoneasylum.com/backlink?for=18364" title="Pages that link to Preserved Topic: Best examples of &amp;#039;cookie&amp;#039; coding (Page 1 of 1)" rel="nofollow" >Preserved Topic: Best examples of &#039;cookie&#039; coding <span class="small">(Page 1 of 1)</span>\

 
DocOzone
Maniac (V) Lord Mad Scientist
Sovereign of all the lands Ozone and just beyond that little green line over there...

From: Stockholm, Sweden
Insane since: Mar 1994

posted posted 10-28-2001 16:57

OK, I've always had a hard time with this, somehow working with cookies always makes me crazy, and the cross-browser aspects of it always get me down. Still, I've scripted myself into a corner, and I need cookies! (I'm hoping to store the position and open windows for my new page, and then restore it upon returning. Mostly just session cookie, but possibly an option for long term cookies as well.)

So! I don't just want pointers to people who have cookie tutorials, I want to ask you for advice, has anyone used any of these examples for yourself, or have you got a killer example I could rip into? Lemme know, I'll be learning this tonight, one way or the other.

Your pal, -doc-

InI
Paranoid (IV) Mad Scientist

From: Somewhere over the rainbow
Insane since: Mar 2001

posted posted 10-28-2001 17:44

The poster has demanded we remove all his contributions, less he takes legal action.
We have done so.
Now Tyberius Prime expects him to start complaining that we removed his 'free speech' since this message will replace all of his posts, past and future.
Don't follow his example - seek real life help first.

Slime
Lunatic (VI) Mad Scientist

From: Massachusetts, USA
Insane since: Mar 2000

posted posted 10-28-2001 18:51

Personally, I'm tired of all those pre-made functions that deal with cookies for you. Here's the very basics of it.

the document.cookie object contains all the cookies that have been set in the past. It returns name=value pairs separated by semicolons. If you've set a few cookies in the past, this property will contain something like "name=value;name=value;name=value". (Note that there's no semicolon after the last name=value pair.

OK, I'm sure you know enough about string manipulation to now read the value of a cookie you've set in the past. (Use String.indexOf(seacrhfor,startat) and String.substr(start,length) and String.substring(start,end). String.split(';') can also be very helpful.) Now here's how to set a cookie, and it's a little harder:

To set a cookie, you assign a value to document.cookie. This is a little weird, since when you assign the value, it doesn't actually *change* the document.cookie property! The browser just uses the information you're assigning to it to make a new cookie, but document.cookie will still return a name=value list as I said above. To set a cookie, use the following syntax:

document.cookie = "name=value; expires=date; path=path; domain=domain; secure";

The name and value are, obviously, the name and value that you want the cookie to have. The rest is a little harder. the expiration date must be written in a special form - this can be easily done by creating a Date object, setting it to when you want the cookie to expire, and then using the Date.toGMTString() function. If you want the cookie to expire immediately, don't include the expires=date in the string at all, or just set the date to the current time. Personally, I usually set the date to something like a year in advance.

The path is the path on your site where the cookie is allowed to be read. By default, the cookie can be read in any file in the same directory or a subdirectory of the one it was created in. I usually just set "path=/".

domain is what domains the cookie is allowed to be read on. I usually just omit this one, but you could use it if you had something like bugtown.ozones.com and you wanted the cookie to be allowed to be read there, you would set "domain=ozones.com".

The word "secure", if it's there, means that the cookie will use a secure connection to save it. I always omit this.

A few notes:

Always use the escape(string) and unescape(string) functions to encode the values of your cookies. Because if the cookie contains a character that's a semicolon, it can mess some stuff up. So before you set the value of the cookie, do something like value=escape(value); just to be safe, and after you read the value of the cookie, do value=unescape(value);.

Browsers are not required to remember more than 300 cookies total, and no more than 20 cookies per server. That means you're only allowed to set 20 cookies - that's not good if you use cookies on a bunch of your pages. On the other hand, browsers are required to allow 4 kilobytes per cookie (counting both name and value). So what you usually want to do is store lots of data in a single cookie. You might do this by making the value of the cookie "name=value;name2=value2;name3=value3;" and then saying value=encode(value);, and then writing the cookie under the name "ourWallsInfo".

That should do it.

Emperor
Maniac (V) Mad Scientist with Finglongers

From: Cell 53, East Wing
Insane since: Jul 2001

posted posted 10-28-2001 20:57

Slime & Ini: Thanks for that they have just been causing me bother (for some reason) and that has helped (I'm off to simplify things - what I was using was overly complex).

Anyone else looking for further resources may also find these handy:
www.cookiecentral.com/faq
http://wsabstract.com/javatutors/cookie.shtml
http://builder.cnet.com/webbuilding/pages/Programming/Kahn/111997/

Slime: That is virtually a tutorial - fancy polishing it up for the GN (I know I'm being cheeky there sorry)?

[edit: URL problems]

Emps


You're my wife now Dave

[This message has been edited by Emperor (edited 10-28-2001).]

DocOzone
Maniac (V) Lord Mad Scientist
Sovereign of all the lands Ozone and just beyond that little green line over there...

From: Stockholm, Sweden
Insane since: Mar 1994

posted posted 10-28-2001 20:57

Wow, that's a great explanation! You read me correctly, I don't want to wade through a very long example so much as I just want to do a frighteningly simple and short cookie call. Always better to understand the basics and just write it yourself! Thanks a bunch, I've got what I need to get started. (I'll probably refer to the MS-examples too, just to see this in action!) Wish me luck, I'm going to give this a go right now.

Your pal, -doc-

InI
Paranoid (IV) Mad Scientist

From: Somewhere over the rainbow
Insane since: Mar 2001

posted posted 10-28-2001 21:08

The poster has demanded we remove all his contributions, less he takes legal action.
We have done so.
Now Tyberius Prime expects him to start complaining that we removed his 'free speech' since this message will replace all of his posts, past and future.
Don't follow his example - seek real life help first.

DocOzone
Maniac (V) Lord Mad Scientist
Sovereign of all the lands Ozone and just beyond that little green line over there...

From: Stockholm, Sweden
Insane since: Mar 1994

posted posted 10-28-2001 23:58

Yah, this was just *too* damned useful, after a couple of false tries I was able to get it up and running rather smoothly. Since I had stored a bunch of variables in a 'name=value;name2=value2;' string, it seemed the simplest solution to set all of my vars to this was to use the dreaded EVAL statement (BWUHahahahaa!!!) on that string, and voila! My vars were ready for me to run with, too cool.

I've set the expire on this cookie very short, just 60 minutes, any longer than that should be at the discretion of the user, no? Now, if I want to set a cookie for this session only, would it be just a matter of setting it to this time right now, or what?

Just to make sure, I'll add my pleas to the others, this really would make a great tutorial, stupid, simple cookies, woo-hoo! (Like Mom used to bake! :-)

Your pal, -doc-

DocOzone
Maniac (V) Lord Mad Scientist
Sovereign of all the lands Ozone and just beyond that little green line over there...

From: Stockholm, Sweden
Insane since: Mar 1994

posted posted 10-29-2001 00:17

Hmm, here's one more dilemma I'm facing. You've mentioned the possibility of saving more than one cookie. Is it possible to set two cookies from the same page, how do I differentiate between them? (I'm thinking one session cookie and one more long term, say one year.) This is looking really special to me right now, loving it, yeah!

Your pal, -doc-

Slime
Lunatic (VI) Mad Scientist

From: Massachusetts, USA
Insane since: Mar 2000

posted posted 10-29-2001 02:06

Hmm, you mentioned using the eval function earlier... from the context, I don't think that's necessary; document.cookie *takes* a string value, so you can just say

document.cookie = "name=" + escape(namevaluepairs) + "; expires=...";

Maybe I misunderstood.

To save cookies with separate expiration dates? Just use separate cookies.

var soon = new Date(); soon.setTime(soon.getTime() + 1000 * 60); // 1000 milliseconds/second * 60 seconds
var longtime = new Date(); longtime.setTime(longtime.getTime() + 1000 * 60 * 60 * 24 * 360); // 1 year
document.cookie = "shortcookie=" + escape("this cookie expires in 60 seconds!") + "; expires=" + soon.toGMTString() + "; path=/;";
document.cookie = "longcookie=" + escape("this cookie expires in a year.") + "; expires=" + longtime.toGMTString() + "; path=/;";

Edit: Oh, I suppose I can make this into a GN tutorial. Give me a little time, I still gotta finish up the new POV-Ray tutorial and get it up and running, and I have all these things that I'm doing half-heartedly right now because I should probably be doing *other* things, and it's all very confusing. So I'll get to it. =)

[This message has been edited by Slime (edited 10-29-2001).]

Dracusis
Maniac (V) Inmate

From: Brisbane, Australia
Insane since: Apr 2001

posted posted 10-29-2001 02:18

Is their a chance that the browser won't accept a cookie if you don't provide all of the details like path= domain= and so on??

I'm just wondering as one of my sites uses cookies to move session data through various pages and since IE 6 came out the cookies just aren't getting stored by the browser. I also found the same thing happened in Opera 5. Could this be because I'm not specifying a path?

I should really start using cookieless sessions......

DocOzone
Maniac (V) Lord Mad Scientist
Sovereign of all the lands Ozone and just beyond that little green line over there...

From: Stockholm, Sweden
Insane since: Mar 1994

posted posted 10-29-2001 02:54

Hmm, no I'm using the eval() statement after I get all the goodies out, like I'll get a string that reads "windowWidth=800;windowOpen=3;etc...". Now I can just go eval(that_string); and all of those variable get set, simple, no? Finally, a good use for the eval() function, could I have found it?


I'm still having a bit of a problem with both Netscape and Mozilla, neither one of them is accepting my cookies, using the following short script...

function setCookie() {
fooStuff = "lastVisit=" + now.getTime() + ";numVisits=" + numVisits + ";windowOpen=" + windowOpen
if (windowOpen) fooStuff = fooStuff + ";" + "scrollPercent="+scrollPercent+";" + "whichWin="+whichWin;
fooStuff = escape(fooStuff);
dateWhen.setTime(now.getTime() + (365 * 24 * 60 * 60 * 1000)); //<-- one year save cookie;
ozoneCookie = "foo=" + fooStuff + ";expires=" + dateWhen.toGMTString() + ";path=/;domain=ozones.com";
document.cookie = ozoneCookie;
}

Any ideas? I'm hoping it'll be something stupid and simple, I excel at errors of that sort!

Your pal, -doc-

Slime
Lunatic (VI) Mad Scientist

From: Massachusetts, USA
Insane since: Mar 2000

posted posted 10-29-2001 03:06

Have both now and dateWhen been predefined like "var dateWhen = new Date();"? dateWhen should be defined *inside* the function, since you're adding something to its time each time the function is run.

If that isn't the problem, try these... remove domain=ozones.com, try a semicolon after domain=ozones.com, or put spaces after all the semicolons in the ozoneCookie variable. Otherwise, I'm not really sure what the problem is...

Oh, but yes, that is an *excellent* use of the eval() function. One of its intended uses, in fact. =)

DocOzone
Maniac (V) Lord Mad Scientist
Sovereign of all the lands Ozone and just beyond that little green line over there...

From: Stockholm, Sweden
Insane since: Mar 1994

posted posted 10-29-2001 04:42

OK, it appeared to be a combination of things, but the main thing was to leave off the 'domain=' string, it doesn't seem to be a property you can set according to the latest reference at http://www.mozilla.org/docs/dom/domref/ - possibly a security decision?

I don't see why anyone could ever hate these yummy little cookies, this is *fun*! I suppose I'll still need to learn how to set a cookie to expire after the session though, some people will insist, heh.

Your pal, -doc-

bunchapixels
Neurotic (0) Inmate
Newly admitted
posted posted 10-29-2001 09:29

hey doc,
cookie expiry is automatic.
if you don't set an expiry, the nthe cookie will only last as long as the browser window is open.
oh, and by the way - each domain, or whatever, is only allowed 20 cookies - but you can bake BIG cookies if you want!
what i didn't realise was WHAT exactly was a cookie. well, it's like this:
document.cookie = "name=bob";
document.cookie = "age=10";
they are two cookies.
so now, document.cookie is: "name=bob;age=10"
ok?
BUT! you CAN get tricky.
you can use variable pairs, and ALL sorts of funky stuff.

ok, here are a few of my little functions:

code:
function saveCookie(cookieName, cookieVal) {
document.cookie = cookieName + "=" + escape(cookieVal);
}


function getCookie() {
cookieString = document.cookie;
cookieArray = cookieString.split(";");
if(cookieString.length>0) quote = new siteCookie(cookieArray);
}


function siteCookie(cookieItems) {
for(i=0; i<cookieItems.length; i++) {
cookieItem = cookieItems[i].split("=");
eval("this." + cookieItem[0] + "= '" + unescape(cookieItem[1]) + "'");
}
}


now.. with this, you can make the most of each cookie, say, by saving a few values in them, like saveCookie('ages','bob=10

InI
Paranoid (IV) Mad Scientist

From: Somewhere over the rainbow
Insane since: Mar 2001

posted posted 10-30-2001 12:31

The poster has demanded we remove all his contributions, less he takes legal action.
We have done so.
Now Tyberius Prime expects him to start complaining that we removed his 'free speech' since this message will replace all of his posts, past and future.
Don't follow his example - seek real life help first.

« BackwardsOnwards »

Show Forum Drop Down Menu