Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Need to set a cookie and a redirect in CGI.pm

by stevee (Acolyte)
on Jun 07, 2011 at 18:37 UTC ( #908544=perlquestion: print w/replies, xml ) Need Help??

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

Greetings learned monks,

I am using CGI.pm. Through the wisdom of fellow monks I sorted out an issue I had yesterday about getting a re-direct to work. The first item you "print" should be the redirect to make it work. However, due to a requirement change, I need to set a cookie before I action the redirect.

The following code fragment does not work, i.e. a cookie is set but no redirect takes place because there has been a "print" before the "redirect".

use strict; use warnings; use CGI; my $q = CGI->new; my $cookie = $q->cookie(-name=>'lizzy', -value=>'Lizzy', -expires=>'+12h'); #my $r=CGI->new; print $q->redirect( -uri => 'http://perl.about.com/' ); print $q->header(-cookie=>$cookie);

Does anyone have any ideas how I can set the cookie and get the redirect to work?

Many thanks

Replies are listed 'Best First'.
Re: Need to set a cookie and a redirect in CGI.pm
by Your Mother (Archbishop) on Jun 07, 2011 at 18:42 UTC
Re: Need to set a cookie and a redirect in CGI.pm
by wind (Priest) on Jun 07, 2011 at 21:31 UTC

    The redirect method works by creating a header, so the second call to header is treated as the main body of the returned page.

    To fix you simply need to include the cookie in the header created by the redirect method as demonstrated in the resource Your Mother linked to:

    use CGI; use strict; use warnings; my $q = CGI->new; my $cookie = $q->cookie( -name=>'lizzy', -value=>'Lizzy', -expires=>'+12h', ); print $q->redirect( -uri => 'http://perl.about.com/', -cookie => $cookie, );

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://908544]
Approved by ww
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2022-07-05 03:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?