Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Perl: http cookies 2

Status
Not open for further replies.

theEclipse

Programmer
Dec 27, 1999
1,190
US
What can you people tell me about cookies with perl?<br>I would like to know how to set them, and how to read them, as well as all of the parameters (ie exp date, domain, etc)<br><br>thanks in advance <p>theEclipse<br><a href=mailto:eclipse_web@hotmail.com>eclipse_web@hotmail.com</a><br><a href=robacarp.webjump.com>robacarp.webjump.com</a><br>**-Trying to build a documentation of a Javascript DOM, crossbrowser, of course. E-mail me if you know of any little known events and/or methods, etc.
 
does anybody want to help me?? please!! <p>theEclipse<br><a href=mailto:eclipse_web@hotmail.com>eclipse_web@hotmail.com</a><br><a href=robacarp.webjump.com>robacarp.webjump.com</a><br>**-Trying to build a documentation of a Javascript DOM, crossbrowser, of course. E-mail me if you know of any little known events and/or methods, etc.
 
Are you using CGI.pm?......Yes?&nbsp;&nbsp;Then,<br><br><FONT FACE=monospace><br>#!/usr/local/bin/perl<br>use CGI;<br>$thisCGI = '/cgi-bin/examples/setCookie'; <font color=red># change to your dir</font><br>$query = new CGI;<br><br>$cookThis = $query-&gt;cookie(-name=&gt;'cookThis');<br>if ($cookThis) <br>&nbsp;&nbsp;&nbsp;&nbsp;{ <br>&nbsp;&nbsp;&nbsp;&nbsp;$cookie = $query-&gt;cookie(-name=&gt;&quot;cookThis&quot;,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-value=&gt;'',<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-expires=&gt;&quot;+1h&quot;);<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br>else<br>&nbsp;&nbsp;&nbsp;&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;$cookie = $query-&gt;cookie(-name=&gt;&quot;cookThis&quot;,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-value=&gt;&quot;Netscape Version&quot;,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-expires=&gt;&quot;+1h&quot;);<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br><br>print $query-&gt;header(-cookie=&gt;$cookie);<br>print &quot;&lt;BR&gt;CookThis is $cookThis&lt;BR&gt;&quot;; <br>print $query-&gt;start_html(-title=&gt;&quot;UPLOAD THIS&quot;);<br>print $query -&gt;start_multipart_form('POST',&quot;$thisCGI&quot;);<br>print '&lt;BR&gt;',$query-&gt;submit('doWhat','cook');<br>print $query-&gt;end_form;<br>print $query-&gt;end_html;<br></font><br><br><br>see the CGI.pm docs for more details.....you can '<i>perldoc CGI.pm</i> ' or see<br><A HREF=" TARGET="_new"> this helps... <p> <br><a href=mailto: > </a><br><a href= > </a><br> keep the rudder amid ship and beware the odd typo
 
thanks. but do you know how to do it without the module? I guess I could upload the module, but I don't really want to. I would like to keep the script's completly independant. <p>theEclipse<br><a href=mailto:eclipse_web@hotmail.com>eclipse_web@hotmail.com</a><br><a href=robacarp.webjump.com>robacarp.webjump.com</a><br>**-Trying to build a documentation of a Javascript DOM, crossbrowser, of course. E-mail me if you know of any little known events and/or methods, etc.
 
Unfortunately, once I started using CGI.pm, I never went back.&nbsp;&nbsp;My first attempts to use cookies were with the module, so I have never done them 'long hand'.&nbsp;&nbsp;Sorry.&nbsp;&nbsp;I would encourage you to think about getting the module.&nbsp;&nbsp;I think it is important to write enought CGI stuff the long way( sans CGI.pm) to get an understanding of how it works and why, but, once that general understanding is acquired, the module makes for some real time savings.&nbsp;&nbsp;&nbsp;Also, I don't think using the module will make your code much less portable.&nbsp;&nbsp;Use of the CGI.pm module is ubiquitous.<br><br>Also, ' might look at &quot;Creating cookies with PERL&quot; section at <A HREF=" TARGET="_new"> <p> <br><a href=mailto: > </a><br><a href= > </a><br> keep the rudder amid ship and beware the odd typo
 
What is a cookie?

A cookie is a chunk of information that you're allowed to save on a client computer.
Normally, for security reasons, you are not allowed access to computers that visit your web page. However, cookies are an exception that allow you to save information on someone's computer in a structured and somewhat limited fashion.

What does a cookie look like?

A cookie consists of a &quot;name=value&quot; pair, such as
USER_ID = 1234

In this case, the cookie is named 'USER_ID', and the value is '1234'.

You can also save information about the cookie, such as

[tab]The cookie's expiration date and time
[tab]The valid domain for the cookie
[tab]The valid server path for the cookie
[tab]Whether or not to use a secure channel for the cookie

A fully specified cookie looks something like this:
TEST_COOKIE=Famous%20Amos; domain=.mydomain.com; path=/; expires=Sat, 11-Mar-2000 22:52:37 GMT; secure


Cool. Now that you know what a cookie looks like, the next step is to show you how to set and get them from your scripts. Don't worry, its easy.



set_cookie


[tab]set_cookie steps through the cookie associative array and sets what ever name/value pairs it finds. This means, in order to set a cookie you have to do something like this:
[tab]$cookie{'color'} = blue;
[tab]&set_cookie($expiration,$domain,$path,$secure);

The arguments are as follows:
[tab]$expiration
[tab]Expiration date of the cookie, expressed in unix time format (seconds since Jan 1, 1970).
[tab]All expiration dates are in Greenwich Mean Time. (Keep this in mind.)
[tab]If you don't want to set any expiration, then use $expiration = &quot;-1&quot;.
[tab]If you want a &quot;permanent&quot; cookie (it lasts until 12/31/1998) then set $expiration = &quot;&quot;

[tab]$domain
[tab]Domain that the cookie data can be sent back to. Ordinarily you would leave this blank or
[tab]$domain = &quot;&quot;. This allows only you to read the cookie.

[tab]$path
[tab]Any file contained within $path (and it's subdirectories) can retreive the data contained within the cookie. For all pages on your server use &quot;/&quot;, however in case of a subdirectory &quot;/subdirectory&quot;.

[tab]$secure
[tab]Secure can either be equal to 0 or 1. If it's not a secure cookie, you can either leave it out, or $secure = 0. If for some reason you want to use secure cookies, set $secure = 1.

Set_cookie must be called before you print &quot;Content-type:
text/html\n\n&quot;;


[tt]sub set_cookie {
# $expires must be in unix time format, if defined. If not defined it sets the expiration to December 31, 1999.
# If you want no expiration date set, set $expires = -1 (this causes the cookie to be deleted when user closes
# his/her browser).

    local($expires,$domain,$path,$sec) = @_;
        local(@days) = &quot;Sun&quot;,&quot;Mon&quot;,&quot;Tue&quot;,&quot;Wed&quot;,&quot;Thu&quot;,&quot;Fri&quot;,&quot;Sat&quot;);
        local(@months) = (&quot;Jan&quot;,&quot;Feb&quot;,&quot;Mar&quot;,&quot;Apr&quot;,&quot;May&quot;,&quot;Jun&quot;,&quot;Jul&quot;,&quot;Aug&quot;,&quot;Sep&quot;,&quot;Oct&quot;,&quot;Nov&quot;,&quot;Dec&quot;);
    local($seconds,$min,$hour,$mday,$mon,$year,$wday) = gmtime($expires) if ($expires > 0); #get date info if expiration set.
    $seconds = &quot;0&quot; . $seconds if $seconds < 10; # formatting of date variables
    $min = &quot;0&quot; . $min if $min < 10;
    $hour = &quot;0&quot; . $hour if $hour < 10;
    local(@secure) = (&quot;&quot;,&quot;secure&quot;); # add security to the cookie if defined. I'm not too sure how this works.
    if (! defined $expires) { $expires = &quot; expires\=Fri, 31-Dec-1999 00:00:00 GMT;&quot;; } # if expiration not set, expire at 12/31/1999
    elsif ($expires == -1) { $expires = &quot;&quot; } # if expiration set to -1, then eliminate expiration of cookie.
    else {
        $year += 1900;
        $expires = &quot;expires\=$days[$wday],
$mday-$months[$mon]-$year $hour:$min:$seconds GMT; &quot;; #form expiration from value passed to function.
    }
    if (! defined $domain) { $domain = $ENV 'SERVER_NAME'}; } #set domain of cookie. Default is current host.
    if (! defined $path) { $path = &quot;/&quot;; } #set default path = &quot;/&quot;
    if (! defined $secure) { $secure = &quot;0&quot;; }
    local($key);
    foreach $key (keys %cookie) {
        $cookie{$key} =~ s/ /+/g; #convert plus to space.
        print &quot;Set-Cookie: $key\=$cookie{$key};
$expires path\=$path; domain\=$domain; $secure[$sec]\n&quot;;
                #print cookie to browser,
                #this must be done *before*    you print any content type headers.
    }
}[/tt]



get_cookie

get_cookie reads the cookies set to the script by the browser. All cookie information is available though the environmental variable HTTP_COOKIE.

To read the cookies, simply call the subroutine &quot;get_cookie&quot; from anywhere in your script.

Cookies are stored in an associative array like so:
[tab][tt]$cookie{name} = value[/tt]

[tt]sub get_cookie {
    local($chip, $val);
    foreach (split(/; /, $ENV{'HTTP_COOKIE'})) {
            # split cookie at each; (cookie format is name=value; name=value; etc...)
            # Convert plus to space (in case of encoding (not necessary, but recommended)
        s/\+/ /g;
            # Split into key and value.
        ($chip, $val) = split(/=/,$_,2); # splits on the first =.
            # Convert %XX from hex numbers to alphanumeric
        $chip =~ s/%([A-Fa-f0-9]{2})/pack(&quot;c&quot;,hex($1))/ge;
        $val =~ s/%([A-Fa-f0-9]{2})/pack(&quot;c&quot;,hex($1))/ge;
            # Associate key and value
        $cookie{$chip} .= &quot;\1&quot; if (defined($cookie{$chip})); # \1 is the multiple separator
        $cookie{$chip} .= $val;
    }
}[/tt]
 
pump-

thanks, thats just what I was looking for! Awesome!

and thanks to all you guys who suggested other soloutions.
 
pump-

Oh wait, I do have three questions:1) what IS a secure cookie?
does it limit it to the specifyed domain?

2)do you have a sub to delete a cookie?

and 3) what should I put for the exipration date, if it is a sesson only cookie? (like a shopping cart?)

thanks again
 
Eclipse:

1) Yes, a cookie can be limited to a specific domain or a specific path on a domain.

2) Yes:

&delete_cookie(&quot;name1&quot;, &quot;name2&quot;);

delete_cookie will delete cookies of the given names. It does so by setting the expiration date in
the past so that the browser will remove the cookie from it's memory.

sub delete_cookie {
# to delete a cookie, simply pass delete_cookie the name of the cookie to delete.
# you may pass delete_cookie more than 1 name at a time.
local(@to_delete) = @_;
local($name);
foreach $name (@to_delete) {
undef $cookie{$name}; #undefines cookie so if you call set_cookie, it doesn't reset the cookie.
print &quot;Set-Cookie: $name=deleted; expires=Thu, 01-Jan-1970 00:00:00 GMT;\n&quot;;
#this also must be done before you print any content type headers.
}
}


3) Well if you want your cookie to be deleted after the session ends then you must set the expiration date to a blank date. eg:

TEST_COOKIE=Famous%20Amos; domain=.mydomain.com; path=/; secure


Hope this help
 
thats not what I asked. I asked what is a secure cookie. in other words, how is it different from a non-secure cookie?
 
If a cookie is secure defines whether or not you want to restrict the transmission of the cookie to a secure server. If this flag is set to '1', by default the cookies you create will only be sent to secure servers by the client.

A cookie is marked secure by putting the word secure at the end of the request. A secure cookie will be sent only to a server offering HTTPS (HTTP over SSL).

Hope this helps
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top