Perl programmer for hire: download my resume (PDF).
John Bokma Perl
freelance Perl programmer

Redirecting with a Perl CGI script

Tutorial with examples | 0 comments

Several simple redirection Perl CGI programs are discussed below. I don't use the CGI module since the overhead of this module for these simple examples is huge.

Redirection basics

Redirection consists just of sending the right headers back to the browser of the visitor. The following is all that is needed to redirect to a fixed URL:

#!/usr/bin/perl
#
# fixedredir.cgi

use strict;
use warnings;


my $URL = "http://www.example.com/";

print "Status: 302 Moved\nLocation: $URL\n\n";

Notice the empty line after the headers which is necessary.

Redirection time dependent

Sometimes it is necessary to redirect visitors based on the current time, for example the hour of the day, or the day of the week.

#!/usr/bin/perl
#
# happyhour.cgi

use strict;
use warnings;


my $hour = (localtime)[2];

my $URL = ($hour > 17 and $hour < 22)
    ?
        "http://yoursite.com/happyhour.html"
    :
        "http://yoursite.com/paymore.html"
    ;

print "Status: 302 Moved\nLocation: $URL\n\n";

When I have a bit more time I will add more examples.

Please post a comment | read 0 comments | RSS feed