spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / perl / mod_perl / chap6 / 2 To page 1To page 2To page 3To page 4To page 5To page 6To page 7current page
[previous]

Practical mod_perl: Chapter 6: Coding with mod_perl in Mind

Sr. Web Developer
mediabistro.com
US-NY-New York

Justtechjobs.com Post A Job | Post A Resume
Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?


Return Codes

Apache::Registry normally assumes a return code of OK (200) and sends it for you. If a different return code needs to be sent, $r->status( ) can be used. For example, to send the return code 404 (Not Found), you can use the following code:

use Apache::Constants qw(NOT_FOUND);
$r->status(NOT_FOUND);

If this method is used, there is no need to call $r->send_http_header( ) (assuming that the PerlSendHeader Off setting is in effect).

Transition from mod_cgi Scripts to Apache Handlers

If you don't need to preserve backward compatibility with mod_cgi, you can port mod_cgi scripts to use mod_perl-specific APIs. This allows you to benefit from features not available under mod_cgi and gives you better performance for the features available under both. We have already seen how easily Apache::Registry turns scripts into handlers before they get executed. The transition to handlers is straightforward in most cases.

Let's see a transition example. We will start with a mod_cgi-compatible script running under Apache::Registry, transpose it into a Perl content handler without using any mod_perl-specific modules, and then convert it to use the Apache::Request and Apache::Cookie modules that are available only in the mod_perl environment.

Starting with a mod_cgi-Compatible Script

Example 6-18 shows the original script's code.

Example 6-18: cookie_script.pl

use strict;
use CGI;
use CGI::Cookie;
use vars qw($q $switch $status $sessionID);
 
init(  );
print_header(  );
print_status(  );
 
sub init {
    $q = new CGI;
    $switch = $q->param("switch") ? 1 : 0;
    my %cookies = CGI::Cookie->fetch;
    $sessionID = exists $cookies{'sessionID'} 
        ? $cookies{'sessionID'}->value
        : '';
 
    # 0 = not running, 1 = running
    $status = $sessionID ? 1 : 0;
    # switch status if asked to
    $status = !$status if $switch;
 
    if ($status) {
        # preserve sessionID if it exists or create a new one
        $sessionID ||= generate_sessionID(  ) if $status;
    } else {
        # delete the sessionID
        $sessionID = '';
    }
} 
 
sub print_header {
    my $c = CGI::Cookie->new(
         -name    => 'sessionID',
         -value   => $sessionID,
         -expires => '+1h'
    );
 
    print $q->header(
         -type   => 'text/html',
         -cookie => $c
    );
}
 
# print the current Session status and a form to toggle the status
sub print_status {
  
    print qq{<html><head><title>Cookie</title></head><body>};
 
    print "<B>Status:</B> ",
        $status
          ? "Session is running with ID: $sessionID"
          : "No session is running";
  
  
    # change status form
    my $button_label = $status ? "Stop" : "Start";
    print qq{<hr>
       <form>
         <input type=submit name=switch value=" $button_label "> 
       </form>
            };
  
    print qq{</body></html>};
    
} 
 
# A dummy ID generator
# Replace with a real session ID generator
########################
sub generate_sessionID {
    return scalar localtime;
} 

The code is very simple. It creates a session when you press the Start button and deletes it when you pressed the Stop button. The session is stored and retrieved using cookies.

We have split the code into three subroutines. init( ) initializes global variables and parses incoming data. print_header( ) prints the HTTP headers, including the cookie header. Finally, print_status( ) generates the output. Later, we will see that this logical separation will allow an easy conversion to Perl content-handler code.

We have used a few global variables, since we didn't want to pass them from function to function. In a big project, you should be very restrictive about what variables are allowed to be global, if any. In any case, the init( ) subroutine makes sure all these variables are reinitialized for each code reinvocation.

We have used a very simple generate_sessionID( ) function that returns a current date-time string (e.g., Wed Apr 12 15:02:23 2000) as a session ID. You'll want to replace this with code that generates a unique and unpredictable session ID each time it is called.

home / programming / perl / mod_perl / chap6 / 2 To page 1To page 2To page 3To page 4To page 5To page 6To page 7current page
[previous]

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business

Created: March 11, 2003
Revised: July 23, 2003

URL: http://webreference.com/programming/perl/mod_perl/chap6/2