Home > Articles > Web Development > Perl

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

3.11. Sending Server Response Headers

You need to send the server response headers.

Technique

Use the send_http_header() method from the Apache class.

package Cookbook::SendWordDoc;

use Apache::Constants qw( OK NOT_FOUND );
use DBI;

use strict;

sub handler {

 my $r = shift;

 my $user = $r->dir_config('DBUSER');
 my $pass = $r->dir_config('DBPASS');
 my $dbase = $r->dir_config('DBASE');

 my $dbh = DBI->connect($dbase, $user, $pass,
  {RaiseError => 1, AutoCommit => 1, PrintError => 1}) or die $DBI::errstr;

 my $sql= qq(
   select document from worddocs
    where name = ?
 );

 # determine the filename the user wants to retrieve
 my ($filename) = $r->path_info =~ m!/(.*)!;

 # do some DBI specific stuff for BLOB fields
 $dbh->{LongReadLen} = 300 * 1024; # 300K

 my $sth = $dbh->prepare($sql);

 $sth->execute($filename);

 my $file = $sth->fetchrow_array;

 $sth->finish;

 return NOT_FOUND unless $file;

 $r->headers_out->set("Content-Disposition" => 
            "inline; filename=$filename");
 $r->send_http_header("application/msword");

 print $file;

 return OK ;
}

1;

Comments

After you have your server response headers in place, you can send them on their way using send_http_header(). It is important to understand that by sending headers you are initiating the start of the response, so any errors that occur after you send your headers will result in a rather unsightly document and will short-circuit Apache's built-in error-handling procedures. For this reason, doing all form field validations, error checking, and so on, prior to calling send_http_header() is considered good programming practice.

One nice thing about send_http_header() is that it accepts the MIME type of the response as an optional argument. This saves you the time of calling $r->content_type() yourself in a separate step or, in the case of legacy CGI scripts, needing to prepend Content-type: text/plain\n\n (or something similar) to your output.

Another convenient feature of the send_http_header() method is that, because it draws on the underlying Apache API, it is platform aware. This means you no longer have to be concerned with whether your script is going to be running on Unix, VMS, or an IBM 390; the proper CRLF character sequence will follow the end of the response headers, allowing for maximum portability (you were concerned, weren't you?).

  • + Share This
  • 🔖 Save To Your Account