jkushner jkushner - 16 days ago 8
Perl Question

cannot read cookie after setting it

For some reason when i try to get into the if cookie exists then redirect function it doesn't enter. Im a perl newb so i have no real answers.

#!/usr/bin/perl -I/srv/www/abc/m/www

require "api";

my $db=db();

use CGI;
use DBI;
use strict;
use warnings;
#use CGI qw(:standard -nph);

# read the CGI params
my $cgi = CGI->new;

my $cookie = $cgi->param("loggedin");
#my $cookie = $cgi->cookie("loggedin");
if($cookie){
print $cgi->redirect("http://host.com");
exit;
}

....

if($userID){
$cgi->cookie(-name=>'loggedin',-value=>'1',-expires=>'+4h',-path=>'/');
print $cgi->redirect("http://host.com");
exit;
}


UPDATE

Id like to determine if the cookie which I set at the bottom of the page is present and if so then perform a redirect. This code is within the
if($cookie)
context.

Answer

Read here to learn how to set and get cookies. Basically:

  • with -value it's setting
  • without -value it's getting

Setting a cookie:

my $cookie = $cgi->cookie( -name    => 'loggedin',
                           -value   => '1',
                           -expires => '+4h',
                           -path    => '/' );
print $cgi->header(-cookie=>$cookie);

Retrieving a cookie:

my $cookie = $cgi->cookie( -name=>'loggedin' );
if ($cookie) {
    # cookie "loggedin" was set
}

Setting a cookie and redirecting:

my $cookie = $cgi->cookie( -name    => 'loggedin',
                           -value   => '1',
                           -expires => '+4h',
                           -path    => '/' );
print $cgi->redirect(
    -uri    => 'http://host.com',
    -status => 302,
    -cookie => $cookie
);

Deleting a cookie and redirecting:

my $cookie = $cgi->cookie( -name    => 'loggedin',
                           -value   => '',
                           -expires => '-1d' );
print $cgi->redirect(
    -uri    => 'http://host.com',
    -status => 302,
    -cookie => $cookie
);

Please note that setting cookies and redirecting at the same time is browser and/or webserver dependent.