Henry Cho
Henry Cho

Reputation: 770

Perl script literally prints http headers instead of understanding them

I couldn't think of better keywords to Google this issue, so I apologize if this is a duplicate.

Here is my logout.pl script that basically erases cookie:

#!/usr/bin/perl -w
use strict;
use warnings;

use CGI;

my $q = new CGI;

print $q->header('text/html');

my $cookie = $q->cookie(
  -name    => 'CGISESSID',
  -value   => '',
  -expires => '-1d'
);

print $q->header(-cookie=>$cookie);
print $q->redirect('welcome.pl');

exit;

When I run this script in a browser, it prints the following:

Set-Cookie: CGISESSID=; path=/; expires=Mon, 17-Feb-2014 09:05:42 GMT Date: Tue, 18 Feb 2014 09:05:42 GMT Content-Type: text/html; charset=ISO-8859-1 Status: 302 Found Location: welcome.pl

What I want, however, is for the browser to delete the cookie and redirect to welcome.pl.

Upvotes: 2

Views: 445

Answers (3)

Ashley
Ashley

Reputation: 4335

There is actually one more problem you might not figure out on your own. The “clear” cookie you’re trying to send to expire the session must be sent with the redirect. The -w switch is not usually what you want, just the use warnings you have too. Also, redirect URLs RFC:MUST be absolute. "welcome.pl" will in most likelihood work but it’s not a good practice and I had relative URIs bite very badly in a modperl app once. So, amended–

#!/usr/bin/env perl
use strict;
use warnings;
use CGI;
use URI;

my $q = CGI->new;

my $cookie = $q->cookie(
  -name    => 'CGISESSID',
  -value   => '',
  -expires => '-1d'
);

my $welcome = URI->new_abs("welcome.pl", $q->url);

print $q->redirect( -uri => $welcome,
                    -cookie => $cookie,
                    -status => 302 );

exit;

Upvotes: 2

Jassi
Jassi

Reputation: 541

You should use $q->header only once in your script and that should be before using anything printable on page

Upvotes: 1

Dave Sherohman
Dave Sherohman

Reputation: 46235

When you print $q->header, that prints all the headers, including the blank line which signals the end of headers, making anything after it content. You need to only print $q->header once, no more.

Upvotes: 8

Related Questions