3 perlfaq9 - Networking ($Revision: 8539 $)
7 This section deals with questions related to networking, the internet,
10 =head2 What is the correct form of response from a CGI script?
12 (Alan Flavell <flavell+www@a5.ph.gla.ac.uk> answers...)
14 The Common Gateway Interface (CGI) specifies a software interface between
15 a program ("CGI script") and a web server (HTTPD). It is not specific
16 to Perl, and has its own FAQs and tutorials, and usenet group,
17 comp.infosystems.www.authoring.cgi
19 The CGI specification is outlined in an informational RFC:
20 http://www.ietf.org/rfc/rfc3875
22 Other relevant documentation listed in: http://www.perl.org/CGI_MetaFAQ.html
24 These Perl FAQs very selectively cover some CGI issues. However, Perl
25 programmers are strongly advised to use the CGI.pm module, to take care
26 of the details for them.
28 The similarity between CGI response headers (defined in the CGI
29 specification) and HTTP response headers (defined in the HTTP
30 specification, RFC2616) is intentional, but can sometimes be confusing.
32 The CGI specification defines two kinds of script: the "Parsed Header"
33 script, and the "Non Parsed Header" (NPH) script. Check your server
34 documentation to see what it supports. "Parsed Header" scripts are
35 simpler in various respects. The CGI specification allows any of the
36 usual newline representations in the CGI response (it's the server's
37 job to create an accurate HTTP response based on it). So "\n" written in
38 text mode is technically correct, and recommended. NPH scripts are more
39 tricky: they must put out a complete and accurate set of HTTP
40 transaction response headers; the HTTP specification calls for records
41 to be terminated with carriage-return and line-feed, i.e ASCII \015\012
42 written in binary mode.
44 Using CGI.pm gives excellent platform independence, including EBCDIC
45 systems. CGI.pm selects an appropriate newline representation
46 ($CGI::CRLF) and sets binmode as appropriate.
48 =head2 My CGI script runs from the command line but not the browser. (500 Server Error)
50 Several things could be wrong. You can go through the "Troubleshooting
51 Perl CGI scripts" guide at
53 http://www.perl.org/troubleshooting_CGI.html
55 If, after that, you can demonstrate that you've read the FAQs and that
56 your problem isn't something simple that can be easily answered, you'll
57 probably receive a courteous and useful reply to your question if you
58 post it on comp.infosystems.www.authoring.cgi (if it's something to do
59 with HTTP or the CGI protocols). Questions that appear to be Perl
60 questions but are really CGI ones that are posted to comp.lang.perl.misc
61 are not so well received.
63 The useful FAQs, related documents, and troubleshooting guides are
64 listed in the CGI Meta FAQ:
66 http://www.perl.org/CGI_MetaFAQ.html
69 =head2 How can I get better error messages from a CGI program?
71 Use the CGI::Carp module. It replaces C<warn> and C<die>, plus the
72 normal Carp modules C<carp>, C<croak>, and C<confess> functions with
73 more verbose and safer versions. It still sends them to the normal
77 warn "This is a complaint";
78 die "But this one is serious";
80 The following use of CGI::Carp also redirects errors to a file of your choice,
81 placed in a BEGIN block to catch compile-time warnings as well:
84 use CGI::Carp qw(carpout);
85 open(LOG, ">>/var/local/cgi-logs/mycgi-log")
86 or die "Unable to append to mycgi-log: $!\n";
90 You can even arrange for fatal errors to go back to the client browser,
91 which is nice for your own debugging, but might confuse the end user.
93 use CGI::Carp qw(fatalsToBrowser);
96 Even if the error happens before you get the HTTP header out, the module
97 will try to take care of this to avoid the dreaded server 500 errors.
98 Normal warnings still go out to the server error log (or wherever
99 you've sent them with C<carpout>) with the application name and date
102 =head2 How do I remove HTML from a string?
104 The most correct way (albeit not the fastest) is to use HTML::Parser
105 from CPAN. Another mostly correct
106 way is to use HTML::FormatText which not only removes HTML but also
107 attempts to do a little simple formatting of the resulting plain text.
109 Many folks attempt a simple-minded regular expression approach, like
110 C<< s/<.*?>//g >>, but that fails in many cases because the tags
111 may continue over line breaks, they may contain quoted angle-brackets,
112 or HTML comment may be present. Plus, folks forget to convert
113 entities--like C<<> for example.
115 Here's one "simple-minded" approach, that works for most files:
117 #!/usr/bin/perl -p0777
118 s/<(?:[^>'"]*|(['"]).*?\1)*>//gs
120 If you want a more complete solution, see the 3-stage striphtml
122 http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz
125 Here are some tricky cases that you should think about when picking
128 <IMG SRC = "foo.gif" ALT = "A > B">
135 <script>if (a<b && a>c)</script>
139 <![INCLUDE CDATA [ >>>>>>>>>>>> ]]>
141 If HTML comments include other tags, those solutions would also break
144 <!-- This section commented out.
145 <B>You can't see me!</B>
148 =head2 How do I extract URLs?
150 You can easily extract all sorts of URLs from HTML with
151 C<HTML::SimpleLinkExtor> which handles anchors, images, objects,
152 frames, and many other tags that can contain a URL. If you need
153 anything more complex, you can create your own subclass of
154 C<HTML::LinkExtor> or C<HTML::Parser>. You might even use
155 C<HTML::SimpleLinkExtor> as an example for something specifically
156 suited to your needs.
158 You can use URI::Find to extract URLs from an arbitrary text document.
160 Less complete solutions involving regular expressions can save
161 you a lot of processing time if you know that the input is simple. One
162 solution from Tom Christiansen runs 100 times faster than most
163 module based approaches but only extracts URLs from anchors where the first
164 attribute is HREF and there are no other attributes.
167 # qxurl - tchrist@perl.com
168 print "$2\n" while m{
170 A \s+ HREF \s* = \s* (["']) (.*?) \1
175 =head2 How do I download a file from the user's machine? How do I open a file on another machine?
177 In this case, download means to use the file upload feature of HTML
178 forms. You allow the web surfer to specify a file to send to your web
179 server. To you it looks like a download, and to the user it looks
180 like an upload. No matter what you call it, you do it with what's
181 known as B<multipart/form-data> encoding. The CGI.pm module (which
182 comes with Perl as part of the Standard Library) supports this in the
183 start_multipart_form() method, which isn't the same as the startform()
186 See the section in the CGI.pm documentation on file uploads for code
187 examples and details.
189 =head2 How do I make an HTML pop-up menu with Perl?
191 (contributed by brian d foy)
193 The CGI.pm module (which comes with Perl) has functions to create
194 the HTML form widgets. See the CGI.pm documentation for more
197 use CGI qw/:standard/;
199 start_html('Favorite Animals'),
202 "What's your favorite animal? ",
205 -values => [ qw( Llama Alpaca Camel Ram ) ]
213 =head2 How do I fetch an HTML file?
215 One approach, if you have the lynx text-based HTML browser installed
216 on your system, is this:
218 $html_code = `lynx -source $url`;
219 $text_data = `lynx -dump $url`;
221 The libwww-perl (LWP) modules from CPAN provide a more powerful way
222 to do this. They don't require lynx, but like lynx, can still work
227 $content = get($URL);
229 # or print HTML from a URL
231 getprint "http://www.linpro.no/lwp/";
233 # or print ASCII from HTML from a URL
234 # also need HTML-Tree package from CPAN
237 use HTML::FormatText;
239 $html = get("http://www.perl.com/");
241 or die "Can't fetch HTML from http://www.perl.com/";
242 $ascii = HTML::FormatText->new->format(parse_html($html));
245 =head2 How do I automate an HTML form submission?
247 If you are doing something complex, such as moving through many pages
248 and forms or a web site, you can use C<WWW::Mechanize>. See its
249 documentation for all the details.
251 If you're submitting values using the GET method, create a URL and encode
252 the form using the C<query_form> method:
257 my $url = url('http://www.perl.com/cgi-bin/cpan_mod');
258 $url->query_form(module => 'DB_File', readme => 1);
259 $content = get($url);
261 If you're using the POST method, create your own user agent and encode
262 the content appropriately.
264 use HTTP::Request::Common qw(POST);
267 $ua = LWP::UserAgent->new();
268 my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod',
269 [ module => 'DB_File', readme => 1 ];
270 $content = $ua->request($req)->as_string;
272 =head2 How do I decode or create those %-encodings on the web?
274 If you are writing a CGI script, you should be using the CGI.pm module
275 that comes with perl, or some other equivalent module. The CGI module
276 automatically decodes queries for you, and provides an escape()
277 function to handle encoding.
279 The best source of detailed information on URI encoding is RFC 2396.
280 Basically, the following substitutions do it:
282 s/([^\w()'*~!.-])/sprintf '%%%02x', ord $1/eg; # encode
284 s/%([A-Fa-f\d]{2})/chr hex $1/eg; # decode
285 s/%([[:xdigit:]]{2})/chr hex $1/eg; # same thing
287 However, you should only apply them to individual URI components, not
288 the entire URI, otherwise you'll lose information and generally mess
289 things up. If that didn't explain it, don't worry. Just go read
290 section 2 of the RFC, it's probably the best explanation there is.
292 RFC 2396 also contains a lot of other useful information, including a
293 regexp for breaking any arbitrary URI into components (Appendix B).
295 =head2 How do I redirect to another page?
297 Specify the complete URL of the destination (even if it is on the same
298 server). This is one of the two different kinds of CGI "Location:"
299 responses which are defined in the CGI specification for a Parsed Headers
300 script. The other kind (an absolute URLpath) is resolved internally to
301 the server without any HTTP redirection. The CGI specifications do not
302 allow relative URLs in either case.
304 Use of CGI.pm is strongly recommended. This example shows redirection
305 with a complete URL. This redirection is handled by the web browser.
307 use CGI qw/:standard/;
309 my $url = 'http://www.cpan.org/';
310 print redirect($url);
313 This example shows a redirection with an absolute URLpath. This
314 redirection is handled by the local web server.
316 my $url = '/CPAN/index.html';
317 print redirect($url);
320 But if coded directly, it could be as follows (the final "\n" is
321 shown separately, for clarity), using either a complete URL or
324 print "Location: $url\n"; # CGI response header
325 print "\n"; # end of headers
328 =head2 How do I put a password on my web pages?
330 To enable authentication for your web server, you need to configure
331 your web server. The configuration is different for different sorts
332 of web servers--apache does it differently from iPlanet which does
333 it differently from IIS. Check your web server documentation for
334 the details for your particular server.
336 =head2 How do I edit my .htpasswd and .htgroup files with Perl?
338 The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a
339 consistent OO interface to these files, regardless of how they're
340 stored. Databases may be text, dbm, Berkeley DB or any database with
341 a DBI compatible driver. HTTPD::UserAdmin supports files used by the
342 "Basic" and "Digest" authentication schemes. Here's an example:
344 use HTTPD::UserAdmin ();
346 ->new(DB => "/foo/.htpasswd")
347 ->add($username => $password);
349 =head2 How do I make sure users can't enter values into a form that cause my CGI script to do bad things?
351 See the security references listed in the CGI Meta FAQ
353 http://www.perl.org/CGI_MetaFAQ.html
355 =head2 How do I parse a mail header?
357 For a quick-and-dirty solution, try this solution derived
358 from L<perlfunc/split>:
362 $header =~ s/\n\s+/ /g; # merge continuation lines
363 %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );
365 That solution doesn't do well if, for example, you're trying to
366 maintain all the Received lines. A more complete approach is to use
367 the Mail::Header module from CPAN (part of the MailTools package).
369 =head2 How do I decode a CGI form?
371 (contributed by brian d foy)
373 Use the CGI.pm module that comes with Perl. It's quick,
374 it's easy, and it actually does quite a bit of work to
375 ensure things happen correctly. It handles GET, POST, and
376 HEAD requests, multipart forms, multivalued fields, query
377 string and message body combinations, and many other things
378 you probably don't want to think about.
380 It doesn't get much easier: the CGI module automatically
381 parses the input and makes each value available through the
384 use CGI qw(:standard);
386 my $total = param( 'price' ) + param( 'shipping' );
388 my @items = param( 'item' ); # multiple values, same field name
390 If you want an object-oriented approach, CGI.pm can do that too.
394 my $cgi = CGI->new();
396 my $total = $cgi->param( 'price' ) + $cgi->param( 'shipping' );
398 my @items = $cgi->param( 'item' );
400 You might also try CGI::Minimal which is a lightweight version
401 of the same thing. Other CGI::* modules on CPAN might work better
404 Many people try to write their own decoder (or copy one from
405 another program) and then run into one of the many "gotchas"
406 of the task. It's much easier and less hassle to use CGI.pm.
408 =head2 How do I check a valid mail address?
410 (partly contributed by Aaron Sherman)
412 This isn't as simple a question as it sounds. There are two parts:
414 a) How do I verify that an email address is correctly formatted?
416 b) How do I verify that an email address targets a valid recipient?
418 Without sending mail to the address and seeing whether there's a human
419 on the other end to answer you, you cannot fully answer part I<b>, but
420 either the C<Email::Valid> or the C<RFC::RFC822::Address> module will do
421 both part I<a> and part I<b> as far as you can in real-time.
423 If you want to just check part I<a> to see that the address is valid
424 according to the mail header standard with a simple regular expression,
425 you can have problems, because there are deliverable addresses that
426 aren't RFC-2822 (the latest mail header standard) compliant, and
427 addresses that aren't deliverable which, are compliant. However, the
428 following will match valid RFC-2822 addresses that do not have comments,
429 folding whitespace, or any other obsolete or non-essential elements.
430 This I<just> matches the address itself:
432 my $atom = qr{[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+};
433 my $dot_atom = qr{$atom(?:\.$atom)*};
434 my $quoted = qr{"(?:\\[^\r\n]|[^\\"])*"};
435 my $local = qr{(?:$dot_atom|$quoted)};
436 my $domain_lit = qr{\[(?:\\\S|[\x21-\x5a\x5e-\x7e])*\]};
437 my $domain = qr{(?:$dot_atom|$domain_lit)};
438 my $addr_spec = qr{$local\@$domain};
440 Just match an address against C</^${addr_spec}$/> to see if it follows
441 the RFC2822 specification. However, because it is impossible to be
442 sure that such a correctly formed address is actually the correct way
443 to reach a particular person or even has a mailbox associated with it,
444 you must be very careful about how you use this.
446 Our best advice for verifying a person's mail address is to have them
447 enter their address twice, just as you normally do to change a
448 password. This usually weeds out typos. If both versions match, send
449 mail to that address with a personal message. If you get the message
450 back and they've followed your directions, you can be reasonably
451 assured that it's real.
453 A related strategy that's less open to forgery is to give them a PIN
454 (personal ID number). Record the address and PIN (best that it be a
455 random one) for later processing. In the mail you send, ask them to
456 include the PIN in their reply. But if it bounces, or the message is
457 included via a "vacation" script, it'll be there anyway. So it's
458 best to ask them to mail back a slight alteration of the PIN, such as
459 with the characters reversed, one added or subtracted to each digit, etc.
461 =head2 How do I decode a MIME/BASE64 string?
463 The MIME-Base64 package (available from CPAN) handles this as well as
464 the MIME/QP encoding. Decoding BASE64 becomes as simple as:
467 $decoded = decode_base64($encoded);
469 The MIME-Tools package (available from CPAN) supports extraction with
470 decoding of BASE64 encoded attachments and content directly from email
473 If the string to decode is short (less than 84 bytes long)
474 a more direct approach is to use the unpack() function's "u"
475 format after minor transliterations:
477 tr#A-Za-z0-9+/##cd; # remove non-base64 chars
478 tr#A-Za-z0-9+/# -_#; # convert to uuencoded format
479 $len = pack("c", 32 + 0.75*length); # compute length byte
480 print unpack("u", $len . $_); # uudecode and print
482 =head2 How do I return the user's mail address?
484 On systems that support getpwuid, the $< variable, and the
485 Sys::Hostname module (which is part of the standard perl distribution),
486 you can probably try using something like this:
489 $address = sprintf('%s@%s', scalar getpwuid($<), hostname);
491 Company policies on mail address can mean that this generates addresses
492 that the company's mail system will not accept, so you should ask for
493 users' mail addresses when this matters. Furthermore, not all systems
494 on which Perl runs are so forthcoming with this information as is Unix.
496 The Mail::Util module from CPAN (part of the MailTools package) provides a
497 mailaddress() function that tries to guess the mail address of the user.
498 It makes a more intelligent guess than the code above, using information
499 given when the module was installed, but it could still be incorrect.
500 Again, the best way is often just to ask the user.
502 =head2 How do I send mail?
504 Use the C<sendmail> program directly:
506 open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
507 or die "Can't fork for sendmail: $!\n";
508 print SENDMAIL <<"EOF";
509 From: User Originating Mail <me\@host>
510 To: Final Destination <you\@otherhost>
511 Subject: A relevant subject line
513 Body of the message goes here after the blank line
514 in as many lines as you like.
516 close(SENDMAIL) or warn "sendmail didn't close nicely";
518 The B<-oi> option prevents sendmail from interpreting a line consisting
519 of a single dot as "end of message". The B<-t> option says to use the
520 headers to decide who to send the message to, and B<-odq> says to put
521 the message into the queue. This last option means your message won't
522 be immediately delivered, so leave it out if you want immediate
525 Alternate, less convenient approaches include calling mail (sometimes
526 called mailx) directly or simply opening up port 25 have having an
527 intimate conversation between just you and the remote SMTP daemon,
530 Or you might be able use the CPAN module Mail::Mailer:
534 $mailer = Mail::Mailer->new();
535 $mailer->open({ From => $from_address,
539 or die "Can't open: $!\n";
543 The Mail::Internet module uses Net::SMTP which is less Unix-centric than
544 Mail::Mailer, but less reliable. Avoid raw SMTP commands. There
545 are many reasons to use a mail transport agent like sendmail. These
546 include queuing, MX records, and security.
548 =head2 How do I use MIME to make an attachment to a mail message?
550 This answer is extracted directly from the MIME::Lite documentation.
551 Create a multipart message (i.e., one with attachments).
555 ### Create a new multipart message:
556 $msg = MIME::Lite->new(
557 From =>'me@myhost.com',
558 To =>'you@yourhost.com',
559 Cc =>'some@other.com, some@more.com',
560 Subject =>'A message with 2 parts...',
561 Type =>'multipart/mixed'
564 ### Add parts (each "attach" has same arguments as "new"):
565 $msg->attach(Type =>'TEXT',
566 Data =>"Here's the GIF file you wanted"
568 $msg->attach(Type =>'image/gif',
569 Path =>'aaa000123.gif',
570 Filename =>'logo.gif'
573 $text = $msg->as_string;
575 MIME::Lite also includes a method for sending these things.
579 This defaults to using L<sendmail> but can be customized to use
580 SMTP via L<Net::SMTP>.
582 =head2 How do I read mail?
584 While you could use the Mail::Folder module from CPAN (part of the
585 MailFolder package) or the Mail::Internet module from CPAN (part
586 of the MailTools package), often a module is overkill. Here's a
593 $/ = ''; # paragraph reads
596 /^Subject:\s*(?:Re:\s*)*(.*)/mi;
597 $sub[++$msgno] = lc($1) || '';
601 for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) {
608 # bysub2 - awkish sort-by-subject
609 BEGIN { $msgno = -1 }
610 $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m;
612 END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }
614 =head2 How do I find out my hostname, domainname, or IP address?
615 X<hostname, domainname, IP address, host, domain, hostfqdn, inet_ntoa,
616 gethostbyname, Socket, Net::Domain, Sys::Hostname>
618 (contributed by brian d foy)
620 The Net::Domain module, which is part of the standard distribution starting
621 in perl5.7.3, can get you the fully qualified domain name (FQDN), the host
622 name, or the domain name.
624 use Net::Domain qw(hostname hostfqdn hostdomain);
626 my $host = hostfqdn();
628 The C<Sys::Hostname> module, included in the standard distribution since
629 perl5.6, can also get the hostname.
635 To get the IP address, you can use the C<gethostbyname> built-in function
636 to turn the name into a number. To turn that number into the dotted octet
637 form (a.b.c.d) that most people expect, use the C<inet_ntoa> function
638 from the <Socket> module, which also comes with perl.
642 my $address = inet_ntoa(
643 scalar gethostbyname( $host || 'localhost' )
646 =head2 How do I fetch a news article or the active newsgroups?
648 Use the Net::NNTP or News::NNTPClient modules, both available from CPAN.
649 This can make tasks like fetching the newsgroup list as simple as
651 perl -MNews::NNTPClient
652 -e 'print News::NNTPClient->new->list("newsgroups")'
654 =head2 How do I fetch/put an FTP file?
656 LWP::Simple (available from CPAN) can fetch but not put. Net::FTP (also
657 available from CPAN) is more complex but can put as well as fetch.
659 =head2 How can I do RPC in Perl?
661 (Contributed by brian d foy)
663 Use one of the RPC modules you can find on CPAN (
664 http://search.cpan.org/search?query=RPC&mode=all ).
668 Revision: $Revision: 8539 $
670 Date: $Date: 2007-01-11 00:07:14 +0100 (jeu, 11 jan 2007) $
672 See L<perlfaq> for source control details and availability.
674 =head1 AUTHOR AND COPYRIGHT
676 Copyright (c) 1997-2007 Tom Christiansen, Nathan Torkington, and
677 other authors as noted. All rights reserved.
679 This documentation is free; you can redistribute it and/or modify it
680 under the same terms as Perl itself.
682 Irrespective of its distribution, all code examples in this file
683 are hereby placed into the public domain. You are permitted and
684 encouraged to use this code in your own programs for fun
685 or for profit as you see fit. A simple comment in the code giving
686 credit would be courteous but is not required.