Home > Articles > Web Development > Perl

This chapter is from the book

This chapter is from the book

Setting the Response Status

You want to tell the client the status of the request by indicating a successful response or an error response, such as a redirect or a server error.

Technique

Use constants exported by the Apache::Constants class to communicate the status of the response back to Apache.

package Cookbook::Regex;

use Apache::Constants qw(:common);
use Apache::File;
use Apache::Log;

use strict;

sub handler {
 
 my $r = shift;

 my $log = $r->server->log;

 my @change = $r->dir_config->get('RegexChange');
 my @to   = $r->dir_config->get('RegexTo');
 
 unless ($r->content_type eq 'text/html') {
  $log->info("Request is not for an html document - skipping...");
  return DECLINED; 
 }

 unless (@change && @to) {
  $log->info("Parameters not set - skipping...");
  return DECLINED; 
 }

 if (@change != @to) {
  $log->error("Number of regex terms do not match!");
  return SERVER_ERROR;
 }

 my $fh = Apache::File->new($r->filename);

 unless ($fh) {
  $log->warn("Cannot open request - skipping... $!");
  return DECLINED;
 }

 $r->send_http_header('text/html');

 while (my $output = ) {
  for (my $i=0; $i < @change; $i++) { 
   $output =~ s/$change[$i]/$to[$i]/eeg;
  }
  print $output;
 }

 return OK;
}
1; 

Comments

Built in to the HTTP/1.1 specification is a series of status codes for communicating the status of the request back to the client. Everyone is familiar with error responses like 404 Not Found and 500 Internal Server Error that appear occasionally while surfing the Web. The 200 OK responses that are the norm typically go by unnoticed, masked by the actual content displayed by the browser. In each of these cases, Apache is returning an HTTP status code through the Status-Line of the server response. Through the mod_perl API we have the ability to control the status of the request by returning the appropriate status as the return value from our handler. Thinking of handlers as functions, not procedures, helps— the return code of the handler defines the status of the request. The Apache::Constants module provides the complete set of response codes as symbolic, human-readable names. These codes are based on the standard HTTP response codes, with the addition of some Apache–specific codes.

It is easiest to begin with the HTTP specific codes. Internally, Apache stores the HTTP status of the request in the status slot of the Apache request record. At the start of each request, the status is set to the constant HTTP_OK, which corresponds to a 200 OK HTTP response. As the different Apache modules step into the request, each has the ability to set the response status to something other than HTTP_OK by returning an HTTP return code. For instance, mod_dir returns HTTP_MOVED_PERMANENTLY whenever a URI is received for a directory but does not contain a trailing slash, such as http://www.example.com/sails. Apache then propagates that response back to the end user in the form of a 301 Moved Permanently response, the browser redirects to the target URI http://www.example.com/sails/, and things continue as normal.

The mechanism is the same for your Perl handlers. Sending a response back to the client with a status other than 200 OK only requires that you return the appropriate HTTP status code back from your handler. These status codes are made available to your code through the Apache::Constants class, which allows you to import each constant by name or use a set of import tags. For instance, we used the :common import tag in the preceding sample handler.

Table 3.8 shows a few of the more common HTTP return codes, along with their Apache::Constants names, suitable for importing into your code. A larger list can be found in Appendix B, whereas the authoritative source is section 10 of RFC 2616.

Table 3.8 Some Apache::Constants Server Response Constants

Apache::Constants Constant

HTTP Response Code

AUTH_REQUIRED

401 Unauthorized

FORBIDDEN

403 Forbidden

NOT_FOUND

404 Not Found

REDIRECT

302 Found

SERVER_ERROR

500 Internal Server Error


Aside from these HTTP return codes, Apache maintains three constants that are meant to help facilitate the interaction between Apache and the various request handlers: OK, DECLINED, and DONE. All of these are also available through the Apache::Constants class. The reason for these Apache-specific codes will become clear in Part III, where we examine the Apache request cycle in detail. For the moment, we can just focus on some mechanics and save the details for later.

The most common return code is OK, which indicates success. Remember that Apache has already set the response to 200 OK, so it generally is not appropriate to return HTTP_OK from your handler—OK is the proper value in nearly all cases. DECLINED tells Apache that you have declined to process the request. This does not necessarily mean that you have not altered the request, only that you have chosen not to inform Apache about it. The final Apache-specific return code is DONE, which indicates that all content has been sent to the client and Apache should immediately skip to the logging phase of the request. DONE is rarely used, but is useful in certain circumstances. Recipe 11.6 shows an interesting application of the DONE return code.

For the most part, all of your handlers will return OK or one of the HTTP-specific error codes, such as REDIRECT or SERVER_ERROR. In reality, Apache treats any return code other than OK, DECLINED, or DONE as an error. While this may sound strange, all it really means is that Apache will start its error response cycle, which allows you to capture responses other than HTTP_OK with an ErrorDocument or the custom response mechanism discussed in Recipe 8.6. Reasons to choose DECLINED over OK as a return code are more fully discussed in later chapters, where each phase of the request cycle has its own peculiarities.

As we have mentioned a few times, Apache::Registry is really a mod_perl handler that wraps your Perl CGI code within a handler() subroutine. One of the side effects of the Apache::Registry design, however, is that any return value from Registry scripts is ignored by Apache::Registry::handler(). This means that the model we have described here does not apply, even though Apache::Registry scripts have access to the entire mod_perl API.

The way around this is to set the status of the request directly using the status() method from the Apache class. For instance, a typical idiom for Registry scripts that use the mod_perl API is:

$r->headers_out(Location => "/pirate_map.html");
$r->status(REDIRECT);
return REDIRECT;

The interesting thing to note here is that, in the case of Registry scripts, the return value actually just serves as a way to exit the script gracefully without any further processing—$r->status(REDIRECT) is the actual mechanism that is telling Apache to return 302 Found back to the client. Actually, it is a bit trickier than that. Apache::Registry returns the status you set with $r->status() back to Apache, then sets $r->status() back to HTTP_OK, because handlers typically do not alter $r->status() directly.

For our example and discussion we have only used a few of the constants available through the Apache::Constants class: Apache::Constants contains over 90 different constants used for the many different aspects of mod_perl, from the server-response codes we have discussed so far to constants only useful when dealing with the internal Apache API. Importing all those constants into your script wastes precious memory and is excessive for all but the most demanding Web application. To make life easier, Apache::Constants defines several import tags that group constants of similar purpose together, such as the :common tag used in the example code. Other convenient tags are listed in the Apache::Constants manpage.

Because every constant you import into your code increases your process size (albeit slightly), you can slim down this list by importing only those constants you actually use:

use Apache::Constants qw(OK REDIRECT SERVER_ERROR);

Not only does this keep unneeded symbols out of your process, as discussed in Chapter 9, but it also increases readability of your code. For the most part, our examples will make use of this more explicit syntax.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020