|
perlfaq9 - Networking ($Revision: 8539 $)
This section deals with questions related to networking, the internet,
and a few on the web.
(Alan Flavell <flavell+www@a5.ph.gla.ac.uk> answers...)
The Common Gateway Interface (CGI) specifies a software interface between
a program ("CGI script") and a web server (HTTPD). It is not specific
to Perl, and has its own FAQs and tutorials, and usenet group,
comp.infosystems.www.authoring.cgi
The CGI specification is outlined in an informational RFC:
http://www.ietf.org/rfc/rfc3875
Other relevant documentation listed in: http://www.perl.org/CGI_MetaFAQ.html
These Perl FAQs very selectively cover some CGI issues. However, Perl
programmers are strongly advised to use the CGI.pm module, to take care
of the details for them.
The similarity between CGI response headers (defined in the CGI
specification) and HTTP response headers (defined in the HTTP
specification, RFC2616) is intentional, but can sometimes be confusing.
The CGI specification defines two kinds of script: the "Parsed Header"
script, and the "Non Parsed Header" (NPH) script. Check your server
documentation to see what it supports. "Parsed Header" scripts are
simpler in various respects. The CGI specification allows any of the
usual newline representations in the CGI response (it's the server's
job to create an accurate HTTP response based on it). So "\n" written in
text mode is technically correct, and recommended. NPH scripts are more
tricky: they must put out a complete and accurate set of HTTP
transaction response headers; the HTTP specification calls for records
to be terminated with carriage-return and line-feed, i.e ASCII \015\012
written in binary mode.
Using CGI.pm gives excellent platform independence, including EBCDIC
systems. CGI.pm selects an appropriate newline representation
($CGI::CRLF) and sets binmode as appropriate.
Several things could be wrong. You can go through the "Troubleshooting
Perl CGI scripts" guide at
http://www.perl.org/troubleshooting_CGI.html
If, after that, you can demonstrate that you've read the FAQs and that
your problem isn't something simple that can be easily answered, you'll
probably receive a courteous and useful reply to your question if you
post it on comp.infosystems.www.authoring.cgi (if it's something to do
with HTTP or the CGI protocols). Questions that appear to be Perl
questions but are really CGI ones that are posted to comp.lang.perl.misc
are not so well received.
The useful FAQs, related documents, and troubleshooting guides are
listed in the CGI Meta FAQ:
http://www.perl.org/CGI_MetaFAQ.html
Use the CGI::Carp module. It replaces warn and die, plus the
normal Carp modules carp, croak, and confess functions with
more verbose and safer versions. It still sends them to the normal
server error log.
use CGI::Carp;
warn "This is a complaint";
die "But this one is serious";
The following use of CGI::Carp also redirects errors to a file of your choice,
placed in a BEGIN block to catch compile-time warnings as well:
BEGIN {
use CGI::Carp qw(carpout);
open(LOG, ">>/var/local/cgi-logs/mycgi-log")
or die "Unable to append to mycgi-log: $!\n";
carpout(*LOG);
}
You can even arrange for fatal errors to go back to the client browser,
which is nice for your own debugging, but might confuse the end user.
use CGI::Carp qw(fatalsToBrowser);
die "Bad error here";
Even if the error happens before you get the HTTP header out, the module
will try to take care of this to avoid the dreaded server 500 errors.
Normal warnings still go out to the server error log (or wherever
you've sent them with carpout) with the application name and date
stamp prepended.
The most correct way (albeit not the fastest) is to use HTML::Parser
from CPAN. Another mostly correct
way is to use HTML::FormatText which not only removes HTML but also
attempts to do a little simple formatting of the resulting plain text.
Many folks attempt a simple-minded regular expression approach, like
s/<.*?>//g, but that fails in many cases because the tags
may continue over line breaks, they may contain quoted angle-brackets,
or HTML comment may be present. Plus, folks forget to convert
entities--like < for example.
Here's one "simple-minded" approach, that works for most files:
#!/usr/bin/perl -p0777
s/<(?:[^>'"]*|(['"]).*?\1)*>//gs
If you want a more complete solution, see the 3-stage striphtml
program in
http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz
.
Here are some tricky cases that you should think about when picking
a solution:
<IMG SRC = "foo.gif" ALT = "A > B">
<IMG SRC = "foo.gif"
ALT = "A > B">
<!-- <A comment> -->
<script>if (a<b && a>c)</script>
<# Just data #>
<![INCLUDE CDATA [ >>>>>>>>>>>> ]]>
If HTML comments include other tags, those solutions would also break
on text like this:
<!-- This section commented out.
<B>You can't see me!</B>
-->
You can easily extract all sorts of URLs from HTML with
HTML::SimpleLinkExtor which handles anchors, images, objects,
frames, and many other tags that can contain a URL. If you need
anything more complex, you can create your own subclass of
HTML::LinkExtor or HTML::Parser. You might even use
HTML::SimpleLinkExtor as an example for something specifically
suited to your needs.
You can use URI::Find to extract URLs from an arbitrary text document.
Less complete solutions involving regular expressions can save
you a lot of processing time if you know that the input is simple. One
solution from Tom Christiansen runs 100 times faster than most
module based approaches but only extracts URLs from anchors where the first
attribute is HREF and there are no other attributes.
print "$2\n" while m{
< \s*
A \s+ HREF \s* = \s* (["']) (.*?) \1
\s* >
}gsix;
In this case, download means to use the file upload feature of HTML
forms. You allow the web surfer to specify a file to send to your web
server. To you it looks like a download, and to the user it looks
like an upload. No matter what you call it, you do it with what's
known as multipart/form-data encoding. The CGI.pm module (which
comes with Perl as part of the Standard Library) supports this in the
start_multipart_form() method, which isn't the same as the startform()
method.
See the section in the CGI.pm documentation on file uploads for code
examples and details.
(contributed by brian d foy)
The CGI.pm module (which comes with Perl) has functions to create
the HTML form widgets. See the CGI.pm documentation for more
examples.
use CGI qw/:standard/;
print header,
start_html('Favorite Animals'),
start_form,
"What's your favorite animal? ",
popup_menu(
-name => 'animal',
-values => [ qw( Llama Alpaca Camel Ram ) ]
),
submit,
end_form,
end_html;
One approach, if you have the lynx text-based HTML browser installed
on your system, is this:
$html_code = `lynx -source $url`;
$text_data = `lynx -dump $url`;
The libwww-perl (LWP) modules from CPAN provide a more powerful way
to do this. They don't require lynx, but like lynx, can still work
through proxies:
use LWP::Simple;
$content = get($URL);
use LWP::Simple;
getprint "http://www.linpro.no/lwp/";
use LWP::Simple;
use HTML::Parser;
use HTML::FormatText;
my ($html, $ascii);
$html = get("http://www.perl.com/");
defined $html
or die "Can't fetch HTML from http://www.perl.com/";
$ascii = HTML::FormatText->new->format(parse_html($html));
print $ascii;
If you are doing something complex, such as moving through many pages
and forms or a web site, you can use WWW::Mechanize. See its
documentation for all the details.
If you're submitting values using the GET method, create a URL and encode
the form using the query_form method:
use LWP::Simple;
use URI::URL;
my $url = url('http://www.perl.com/cgi-bin/cpan_mod');
$url->query_form(module => 'DB_File', readme => 1);
$content = get($url);
If you're using the POST method, create your own user agent and encode
the content appropriately.
use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
$ua = LWP::UserAgent->new();
my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod',
[ module => 'DB_File', readme => 1 ];
$content = $ua->request($req)->as_string;
If you are writing a CGI script, you should be using the CGI.pm module
that comes with perl, or some other equivalent module. The CGI module
automatically decodes queries for you, and provides an escape()
function to handle encoding.
The best source of detailed information on URI encoding is RFC 2396.
Basically, the following substitutions do it:
s/([^\w()'*~!.-])/sprintf '%%%02x', ord $1/eg;
s/%([A-Fa-f\d]{2})/chr hex $1/eg;
s/%([[:xdigit:]]{2})/chr hex $1/eg;
However, you should only apply them to individual URI components, not
the entire URI, otherwise you'll lose information and generally mess
things up. If that didn't explain it, don't worry. Just go read
section 2 of the RFC, it's probably the best explanation there is.
RFC 2396 also contains a lot of other useful information, including a
regexp for breaking any arbitrary URI into components (Appendix B).
Specify the complete URL of the destination (even if it is on the same
server). This is one of the two different kinds of CGI "Location:"
responses which are defined in the CGI specification for a Parsed Headers
script. The other kind (an absolute URLpath) is resolved internally to
the server without any HTTP redirection. The CGI specifications do not
allow relative URLs in either case.
Use of CGI.pm is strongly recommended. This example shows redirection
with a complete URL. This redirection is handled by the web browser.
use CGI qw/:standard/;
my $url = 'http://www.cpan.org/';
print redirect($url);
This example shows a redirection with an absolute URLpath. This
redirection is handled by the local web server.
my $url = '/CPAN/index.html';
print redirect($url);
But if coded directly, it could be as follows (the final "\n" is
shown separately, for clarity), using either a complete URL or
an absolute URLpath.
print "Location: $url\n";
print "\n";
To enable authentication for your web server, you need to configure
your web server. The configuration is different for different sorts
of web servers--apache does it differently from iPlanet which does
it differently from IIS. Check your web server documentation for
the details for your particular server.
The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a
consistent OO interface to these files, regardless of how they're
stored. Databases may be text, dbm, Berkeley DB or any database with
a DBI compatible driver. HTTPD::UserAdmin supports files used by the
"Basic" and "Digest" authentication schemes. Here's an example:
use HTTPD::UserAdmin ();
HTTPD::UserAdmin
->new(DB => "/foo/.htpasswd")
->add($username => $password);
See the security references listed in the CGI Meta FAQ
http://www.perl.org/CGI_MetaFAQ.html
For a quick-and-dirty solution, try this solution derived
from split in the perlfunc manpage:
$/ = '';
$header = <MSG>;
$header =~ s/\n\s+/ /g;
%head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );
That solution doesn't do well if, for example, you're trying to
maintain all the Received lines. A more complete approach is to use
the Mail::Header module from CPAN (part of the MailTools package).
(contributed by brian d foy)
Use the CGI.pm module that comes with Perl. It's quick,
it's easy, and it actually does quite a bit of work to
ensure things happen correctly. It handles GET, POST, and
HEAD requests, multipart forms, multivalued fields, query
string and message body combinations, and many other things
you probably don't want to think about.
It doesn't get much easier: the CGI module automatically
parses the input and makes each value available through the
param() function.
use CGI qw(:standard);
my $total = param( 'price' ) + param( 'shipping' );< |