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

I've recently started using CGI.pm for its cookie support over my own home-brew functions. I am having trouble figuring out how to redirect a browser to another page though. Previously this would work:
print "Location: $url\n\n";

However, after I use CGI.pm to set a cookie, it no longer works and just prints it to the web browser as part of the page.

I tried using:
print query->redirect('http://somewhere.else/in/movie/land');"

But this did not work. The documentation says that you cannot set a header and use the redirect. What is the best way to get this done? I could just have it open the html file I want it to display and print it out to the browser, but there is at least 1 instance when I will have to redirect to another server.

Replies are listed 'Best First'.
Re: Redirects and CGI.pm
by LTjake (Prior) on Oct 02, 2002 at 19:12 UTC
    redirect is just like header
    print $q->redirect( -uri => $new_url, -cookie => $cookie );
    It would be nice if you would provide some code so we could diagnose what exactly is wrong with it.
Re: Redirects and CGI.pm
by dws (Chancellor) on Oct 02, 2002 at 18:55 UTC
    However, after I use CGI.pm to set a cookie, it no longer works and just prints it to the web browser as part of the page.

    Show us your code. Strip it down to a small example that demonstrates the problem.

      my $query = CGI::new(); my $cookie_name = $query->cookie(-name => 'MYHASH', -value => \%hash); print $query->header(-cookie=>$cookie_name); print query->redirect('http://somewhere.else/in/movie/land');
      code. The second answer, stating that redirect & header are basicallyt he same is what i needed. Thank you.
        Therein lies your problem. A redirect is part of the HTTP header; once you print the header (via the header() method) you can't print another one. Try:

        print $query->header(-cookie => $cookie_name, -location => 'http://www.somewhere-else.com/');
Re: Redirects and CGI.pm
by charnos (Friar) on Oct 02, 2002 at 19:16 UTC
    Two thoughts (just off the top of my head):
    • Set the cookie (which sends a header, IIRC), then print a blank page with a meta refresh tag, using the redirect url and a short (1 second may be the smallest increment) refresh time.

    • or..
    • Set the cookie, then use something like LWP::Simple to get the contents of the redirected page and print that. One caveat though, if the redirected site isn't your own, they may not appreciate this (though I assume if you're redirecting to another site, you're probably the owner of the other site as well).
    Just a thought on the matter, good luck! :)