Spidy has asked for the wisdom of the Perl Monks concerning the following question:

Can anyone explain cookies to me? I want to be able to write and read cookies with Perl, in order to check if a user is logged in or not.

Thanks,
Spidy

20040908 Edit by castaway: Changed title from 'Cookies?'

Replies are listed 'Best First'.
Re: How do I use HTTP Cookies?
by edoc (Chaplain) on Aug 30, 2004 at 02:40 UTC
Re: How do I use HTTP Cookies?
by bradcathey (Prior) on Aug 30, 2004 at 03:53 UTC

    I let CGI do the job:

    use CGI; my $query = new CGI; my $user = $justloggedin; my $newcookie = $query->cookie( -name => 'arbitrarycookiename', -value => $user, -expires => '+15m'); #no activity in 15min...gone! print $query->header(-cookie => $newcookie); #write it

    then read it later

    my $user = $query->cookie('arbitrarycookiename'); #read it if ($user) { $stillloggedin } else { &loggin() }

    —Brad
    "Don't ever take a fence down until you know the reason it was put up." G. K. Chesterton
      Your version seems to make the most sense to me so far...

      I need a few things explained though. These are the lines:
      my $user = $justloggedin;

      my $newcookie = $query->cookie( -name => 'arbitrarycookiename', -value => $user, -expires => '+15m'); #no activity in 15min...gone! my $user = $query->cookie('arbitrarycookiename'); #read it if ($user) { $stillloggedin } else { &loggin() }

      Otherwise, I'm pretty sure I understand most of it...what are $query and $stillloggedin doing? (&loggin() is trying to log in if it didn't work, right?)
        'I need a few things explained though. These are the lines'

        Those are all of the 'lines' that deal with the cookie. So all I got from your reply is that you know how to decalare variables and write a print statement? As far as your question about query:

        $query: This will parse the input (from both POST and GET methods) and store it into a perl5 object called $query.

        As read in the POD. I think $stilllogged should be pretty intuitive. Have you looked at any of the documentation of CGI or CGI::Cookie yet (as we asked in the beginning)? I am not being condescending, but it sounds like that is where you need to start. It is critical you can understand what you are using or trying to use so we can help you. The documentation usually can answer many of your questions quite quickly.

        Expanded, that 1st line is showing that you are receiving the user's name as input from an HTML form. So...

        my $user = $query->param('username');

        You can keep this in a hidden field in the form.

        $query

        is an arbitrary, but oftused name for the CGI session variable. Read all about it in the CGI docs.

        $stillloggedin

        ...simply represents what redirection you would use if the user is found in the cookie, indicating their cookie has not timed out and that they are still logged in. Otherwise (&loggin), take them to an HTML form where they have to re-log-in.

        Update: Check out Ovid's CGI course, as well the CGI Tutorials here in the Monastery. Super Searching will find enough on the topic to choke a horse. Also, bear in mind, what I have presented is a very simple solution. It is not secure (though the username is less important this way than the password—another huge topic among monks). There are more complicated scenarios using a database, in combination with cookies, to track who's logged in, etc. Cookies are not always enabled, so database methods might be invoked, and beyond the scope of this thread. (Update 2: fixed typos in my first Update—where's Preview when you need it :^)


        —Brad
        "Don't ever take a fence down until you know the reason it was put up." G. K. Chesterton
Re: How do I use HTTP Cookies?
by csuhockey3 (Curate) on Aug 30, 2004 at 02:43 UTC
    Have you looked at CGI::Cookie or HTTP::Cookies::Microsoft.
    I also found this here on PM (if you don't wan't to/can't use CGI) but I would stick to CGI::Cookie.

    update: Forgot to add the tutorial link I used a while back, Have a look at this tutorial, this should better answer your question.
Re: How do I use HTTP Cookies?
by nedals (Deacon) on Aug 30, 2004 at 07:29 UTC

    I would guess by your last response, that you are not really getting this. So let me have a stab at the risk of being lambasted by those who know far more than I do.

    Firstly, are you familiar with..
    use CGI;

    or are you still using some form of &read_form() subroutine to get your <form> data? If so, stop using it immediately (or sooner.)

    Use this instead...
    use CGI;
    my $query = new CGI;
    my $form_data = $query->param('field_name'); ## That's all you need to get form data

    ... and if you are wondering what the 'my' is, then you are NOT using 'strict'. Strict will more closely contol the 'scope' of your variables and will prevent stupid spelling mistakes.

    ALL your CGI perl scripts should begin with...
    use strict;
    use CGI;
    my $query = new CGI;

    Most of the responses in this thread assume a knowledge of CGI. I use very little of CGI's capabilities. I mainly use it to get data from my <form> and cookies. So here's an easily understood approach to set and read a simple, session-persistant cookie.

    Set a cookie:
    my $cookie = "cookie_name=some_value"; # a cookie is simply a name/value pair
    print "Content-Type: text/html\n";
    print "Set-Cookie: $cookie\n\n";

    Read a cookie:
    my $cookie = $query->cookie('cookie_name'); # using CGI

    Clear a cookie:
    my $cookie = "cookie_name='';expires=01 Jan 2000 00:00:00";

    This is really basic but should be enough to get you started. Next you will need to read up on cookies in general. There a lot more to learn.

      Wow. That's a really helpful explanation, and most of it makes sense to me now. Thank you!


      could I use this instead?:
      my $query=param('field name');
Re: How do I use HTTP How do I use HTTP Cookies?
by Spidy (Chaplain) on Aug 30, 2004 at 03:15 UTC
    I still don't quite understand it....Could anyone give me an easy to understand example of writing a cookie, checking to see if a cookie exists, and deleting/clearing a cookie?

    Thanks,
    Spidy
      This might be better, as is it breaks down a working example. Do you have a good grasp of documentation and/or modules? As far a clearing the cookie, that is done by the expiration date. Have you tried anything on your own yet? If you have, we can help you more easily if you post some of your code that is giving you trouble.

      CSUhockey3
        I haven't tried anything with cookies yet, no. I want to start trying to do some cookie stuff, so I can actually have users stay logged in a bit more securely than including their username and password in an URL.

      You delete cookies by setting an expiration date that is a date prior to the date/time the cookie is being set. Or, set the cookie with no expiration date (in which case it will be deleted when the browser is closed).

      The rest of this that question was answered by the POD for CGI::Cookie, already pointed out in a previous followup. I see within that documentation, examples of creating cookies, retrieving cookies (which is the first step toward checking for the existance of one), and (through setting expiration date) dismissing them.


      Dave

Re: How do I use HTTP Cookies?
by rawjoeshaw (Sexton) on Aug 30, 2004 at 16:07 UTC
    Script Archive has a good library I use, along with good examples I was able to read through and understand. You can use his library to perform function calls for all your cookie management.

    Basically, whenever you set a cookie to a user, it has a name and a value. Whenever a user visits you domain, all cookies are passed to your server that were set by your domain.

    So if you want to send a cookie, you call the function to set the expiration date at whatever you want, print your http header, and between the two end-of-lines of the header, call the setCookie function. The set function will take a name-value pair (as many as you want to pass) and sets those cookies onto the client.

    To remove cookies, you'd do the same as above only set the date for some time in the past. Then it will delete cookies with those names off the client.

    To get a cookie, you just call the getCookie function. That returns a true or false if the cookie exists. To get the actual value of the cookie, you would use the line $valueIwant = $Cookies{'cookieName'}; that way you can set multiple cookies to a client and get them.

    Again, the README and counter example should help you work through it. Good luck.

      I wouldn't recommend MSA scripts -- they have known problems with security (among other things). Instead I'd recommend beginners start with the NMS scripts.