source: for-distributions/trunk/bin/windows/perl/lib/Pod/perlfaq9.pod@ 14489

Last change on this file since 14489 was 14489, checked in by oranfry, 17 years ago

upgrading to perl 5.8

File size: 23.9 KB
Line 
1=head1 NAME
2
3perlfaq9 - Networking ($Revision: 1.28 $, $Date: 2005/12/31 00:54:37 $)
4
5=head1 DESCRIPTION
6
7This section deals with questions related to networking, the internet,
8and a few on the web.
9
10=head2 What is the correct form of response from a CGI script?
11
12(Alan Flavell <[email protected]> answers...)
13
14The Common Gateway Interface (CGI) specifies a software interface between
15a program ("CGI script") and a web server (HTTPD). It is not specific
16to Perl, and has its own FAQs and tutorials, and usenet group,
17comp.infosystems.www.authoring.cgi
18
19The CGI specification is outlined in an informational RFC:
20http://www.ietf.org/rfc/rfc3875
21
22Other relevant documentation listed in: http://www.perl.org/CGI_MetaFAQ.html
23
24These Perl FAQs very selectively cover some CGI issues. However, Perl
25programmers are strongly advised to use the CGI.pm module, to take care
26of the details for them.
27
28The similarity between CGI response headers (defined in the CGI
29specification) and HTTP response headers (defined in the HTTP
30specification, RFC2616) is intentional, but can sometimes be confusing.
31
32The CGI specification defines two kinds of script: the "Parsed Header"
33script, and the "Non Parsed Header" (NPH) script. Check your server
34documentation to see what it supports. "Parsed Header" scripts are
35simpler in various respects. The CGI specification allows any of the
36usual newline representations in the CGI response (it's the server's
37job to create an accurate HTTP response based on it). So "\n" written in
38text mode is technically correct, and recommended. NPH scripts are more
39tricky: they must put out a complete and accurate set of HTTP
40transaction response headers; the HTTP specification calls for records
41to be terminated with carriage-return and line-feed, i.e ASCII \015\012
42written in binary mode.
43
44Using CGI.pm gives excellent platform independence, including EBCDIC
45systems. CGI.pm selects an appropriate newline representation
46($CGI::CRLF) and sets binmode as appropriate.
47
48=head2 My CGI script runs from the command line but not the browser. (500 Server Error)
49
50Several things could be wrong. You can go through the "Troubleshooting
51Perl CGI scripts" guide at
52
53 http://www.perl.org/troubleshooting_CGI.html
54
55If, after that, you can demonstrate that you've read the FAQs and that
56your problem isn't something simple that can be easily answered, you'll
57probably receive a courteous and useful reply to your question if you
58post it on comp.infosystems.www.authoring.cgi (if it's something to do
59with HTTP or the CGI protocols). Questions that appear to be Perl
60questions but are really CGI ones that are posted to comp.lang.perl.misc
61are not so well received.
62
63The useful FAQs, related documents, and troubleshooting guides are
64listed in the CGI Meta FAQ:
65
66 http://www.perl.org/CGI_MetaFAQ.html
67
68
69=head2 How can I get better error messages from a CGI program?
70
71Use the CGI::Carp module. It replaces C<warn> and C<die>, plus the
72normal Carp modules C<carp>, C<croak>, and C<confess> functions with
73more verbose and safer versions. It still sends them to the normal
74server error log.
75
76 use CGI::Carp;
77 warn "This is a complaint";
78 die "But this one is serious";
79
80The following use of CGI::Carp also redirects errors to a file of your choice,
81placed in a BEGIN block to catch compile-time warnings as well:
82
83 BEGIN {
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";
87 carpout(*LOG);
88 }
89
90You can even arrange for fatal errors to go back to the client browser,
91which is nice for your own debugging, but might confuse the end user.
92
93 use CGI::Carp qw(fatalsToBrowser);
94 die "Bad error here";
95
96Even if the error happens before you get the HTTP header out, the module
97will try to take care of this to avoid the dreaded server 500 errors.
98Normal warnings still go out to the server error log (or wherever
99you've sent them with C<carpout>) with the application name and date
100stamp prepended.
101
102=head2 How do I remove HTML from a string?
103
104The most correct way (albeit not the fastest) is to use HTML::Parser
105from CPAN. Another mostly correct
106way is to use HTML::FormatText which not only removes HTML but also
107attempts to do a little simple formatting of the resulting plain text.
108
109Many folks attempt a simple-minded regular expression approach, like
110C<< s/<.*?>//g >>, but that fails in many cases because the tags
111may continue over line breaks, they may contain quoted angle-brackets,
112or HTML comment may be present. Plus, folks forget to convert
113entities--like C<&lt;> for example.
114
115Here's one "simple-minded" approach, that works for most files:
116
117 #!/usr/bin/perl -p0777
118 s/<(?:[^>'"]*|(['"]).*?\1)*>//gs
119
120If you want a more complete solution, see the 3-stage striphtml
121program in
122http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz
123.
124
125Here are some tricky cases that you should think about when picking
126a solution:
127
128 <IMG SRC = "foo.gif" ALT = "A > B">
129
130 <IMG SRC = "foo.gif"
131 ALT = "A > B">
132
133 <!-- <A comment> -->
134
135 <script>if (a<b && a>c)</script>
136
137 <# Just data #>
138
139 <![INCLUDE CDATA [ >>>>>>>>>>>> ]]>
140
141If HTML comments include other tags, those solutions would also break
142on text like this:
143
144 <!-- This section commented out.
145 <B>You can't see me!</B>
146 -->
147
148=head2 How do I extract URLs?
149
150You can easily extract all sorts of URLs from HTML with
151C<HTML::SimpleLinkExtor> which handles anchors, images, objects,
152frames, and many other tags that can contain a URL. If you need
153anything more complex, you can create your own subclass of
154C<HTML::LinkExtor> or C<HTML::Parser>. You might even use
155C<HTML::SimpleLinkExtor> as an example for something specifically
156suited to your needs.
157
158You can use URI::Find to extract URLs from an arbitrary text document.
159
160Less complete solutions involving regular expressions can save
161you a lot of processing time if you know that the input is simple. One
162solution from Tom Christiansen runs 100 times faster than most
163module based approaches but only extracts URLs from anchors where the first
164attribute is HREF and there are no other attributes.
165
166 #!/usr/bin/perl -n00
167 # qxurl - [email protected]
168 print "$2\n" while m{
169 < \s*
170 A \s+ HREF \s* = \s* (["']) (.*?) \1
171 \s* >
172 }gsix;
173
174
175=head2 How do I download a file from the user's machine? How do I open a file on another machine?
176
177In this case, download means to use the file upload feature of HTML
178forms. You allow the web surfer to specify a file to send to your web
179server. To you it looks like a download, and to the user it looks
180like an upload. No matter what you call it, you do it with what's
181known as B<multipart/form-data> encoding. The CGI.pm module (which
182comes with Perl as part of the Standard Library) supports this in the
183start_multipart_form() method, which isn't the same as the startform()
184method.
185
186See the section in the CGI.pm documentation on file uploads for code
187examples and details.
188
189=head2 How do I make a pop-up menu in HTML?
190
191Use the B<< <SELECT> >> and B<< <OPTION> >> tags. The CGI.pm
192module (available from CPAN) supports this widget, as well as many
193others, including some that it cleverly synthesizes on its own.
194
195=head2 How do I fetch an HTML file?
196
197One approach, if you have the lynx text-based HTML browser installed
198on your system, is this:
199
200 $html_code = `lynx -source $url`;
201 $text_data = `lynx -dump $url`;
202
203The libwww-perl (LWP) modules from CPAN provide a more powerful way
204to do this. They don't require lynx, but like lynx, can still work
205through proxies:
206
207 # simplest version
208 use LWP::Simple;
209 $content = get($URL);
210
211 # or print HTML from a URL
212 use LWP::Simple;
213 getprint "http://www.linpro.no/lwp/";
214
215 # or print ASCII from HTML from a URL
216 # also need HTML-Tree package from CPAN
217 use LWP::Simple;
218 use HTML::Parser;
219 use HTML::FormatText;
220 my ($html, $ascii);
221 $html = get("http://www.perl.com/");
222 defined $html
223 or die "Can't fetch HTML from http://www.perl.com/";
224 $ascii = HTML::FormatText->new->format(parse_html($html));
225 print $ascii;
226
227=head2 How do I automate an HTML form submission?
228
229If you are doing something complex, such as moving through many pages
230and forms or a web site, you can use C<WWW::Mechanize>. See its
231documentation for all the details.
232
233If you're submitting values using the GET method, create a URL and encode
234the form using the C<query_form> method:
235
236 use LWP::Simple;
237 use URI::URL;
238
239 my $url = url('http://www.perl.com/cgi-bin/cpan_mod');
240 $url->query_form(module => 'DB_File', readme => 1);
241 $content = get($url);
242
243If you're using the POST method, create your own user agent and encode
244the content appropriately.
245
246 use HTTP::Request::Common qw(POST);
247 use LWP::UserAgent;
248
249 $ua = LWP::UserAgent->new();
250 my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod',
251 [ module => 'DB_File', readme => 1 ];
252 $content = $ua->request($req)->as_string;
253
254=head2 How do I decode or create those %-encodings on the web?
255
256If you are writing a CGI script, you should be using the CGI.pm module
257that comes with perl, or some other equivalent module. The CGI module
258automatically decodes queries for you, and provides an escape()
259function to handle encoding.
260
261The best source of detailed information on URI encoding is RFC 2396.
262Basically, the following substitutions do it:
263
264 s/([^\w()'*~!.-])/sprintf '%%%02x', ord $1/eg; # encode
265
266 s/%([A-Fa-f\d]{2})/chr hex $1/eg; # decode
267 s/%([[:xdigit:]]{2})/chr hex $1/eg; # same thing
268
269However, you should only apply them to individual URI components, not
270the entire URI, otherwise you'll lose information and generally mess
271things up. If that didn't explain it, don't worry. Just go read
272section 2 of the RFC, it's probably the best explanation there is.
273
274RFC 2396 also contains a lot of other useful information, including a
275regexp for breaking any arbitrary URI into components (Appendix B).
276
277=head2 How do I redirect to another page?
278
279Specify the complete URL of the destination (even if it is on the same
280server). This is one of the two different kinds of CGI "Location:"
281responses which are defined in the CGI specification for a Parsed Headers
282script. The other kind (an absolute URLpath) is resolved internally to
283the server without any HTTP redirection. The CGI specifications do not
284allow relative URLs in either case.
285
286Use of CGI.pm is strongly recommended. This example shows redirection
287with a complete URL. This redirection is handled by the web browser.
288
289 use CGI qw/:standard/;
290
291 my $url = 'http://www.cpan.org/';
292 print redirect($url);
293
294
295This example shows a redirection with an absolute URLpath. This
296redirection is handled by the local web server.
297
298 my $url = '/CPAN/index.html';
299 print redirect($url);
300
301
302But if coded directly, it could be as follows (the final "\n" is
303shown separately, for clarity), using either a complete URL or
304an absolute URLpath.
305
306 print "Location: $url\n"; # CGI response header
307 print "\n"; # end of headers
308
309
310=head2 How do I put a password on my web pages?
311
312To enable authentication for your web server, you need to configure
313your web server. The configuration is different for different sorts
314of web servers---apache does it differently from iPlanet which does
315it differently from IIS. Check your web server documentation for
316the details for your particular server.
317
318=head2 How do I edit my .htpasswd and .htgroup files with Perl?
319
320The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a
321consistent OO interface to these files, regardless of how they're
322stored. Databases may be text, dbm, Berkeley DB or any database with
323a DBI compatible driver. HTTPD::UserAdmin supports files used by the
324"Basic" and "Digest" authentication schemes. Here's an example:
325
326 use HTTPD::UserAdmin ();
327 HTTPD::UserAdmin
328 ->new(DB => "/foo/.htpasswd")
329 ->add($username => $password);
330
331=head2 How do I make sure users can't enter values into a form that cause my CGI script to do bad things?
332
333See the security references listed in the CGI Meta FAQ
334
335 http://www.perl.org/CGI_MetaFAQ.html
336
337=head2 How do I parse a mail header?
338
339For a quick-and-dirty solution, try this solution derived
340from L<perlfunc/split>:
341
342 $/ = '';
343 $header = <MSG>;
344 $header =~ s/\n\s+/ /g; # merge continuation lines
345 %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );
346
347That solution doesn't do well if, for example, you're trying to
348maintain all the Received lines. A more complete approach is to use
349the Mail::Header module from CPAN (part of the MailTools package).
350
351=head2 How do I decode a CGI form?
352
353(contributed by brian d foy)
354
355Use the CGI.pm module that comes with Perl. It's quick,
356it's easy, and it actually does quite a bit of work to
357ensure things happen correctly. It handles GET, POST, and
358HEAD requests, multipart forms, multivalued fields, query
359string and message body combinations, and many other things
360you probably don't want to think about.
361
362It doesn't get much easier: the CGI module automatically
363parses the input and makes each value available through the
364C<param()> function.
365
366 use CGI qw(:standard);
367
368 my $total = param( 'price' ) + param( 'shipping' );
369
370 my @items = param( 'item' ); # multiple values, same field name
371
372If you want an object-oriented approach, CGI.pm can do that too.
373
374 use CGI;
375
376 my $cgi = CGI->new();
377
378 my $total = $cgi->param( 'price' ) + $cgi->param( 'shipping' );
379
380 my @items = $cgi->param( 'item' );
381
382You might also try CGI::Minimal which is a lightweight version
383of the same thing. Other CGI::* modules on CPAN might work better
384for you, too.
385
386Many people try to write their own decoder (or copy one from
387another program) and then run into one of the many "gotchas"
388of the task. It's much easier and less hassle to use CGI.pm.
389
390=head2 How do I check a valid mail address?
391
392You can't, at least, not in real time. Bummer, eh?
393
394Without sending mail to the address and seeing whether there's a human
395on the other end to answer you, you cannot determine whether a mail
396address is valid. Even if you apply the mail header standard, you
397can have problems, because there are deliverable addresses that aren't
398RFC-822 (the mail header standard) compliant, and addresses that aren't
399deliverable which are compliant.
400
401You can use the Email::Valid or RFC::RFC822::Address which check
402the format of the address, although they cannot actually tell you
403if it is a deliverable address (i.e. that mail to the address
404will not bounce). Modules like Mail::CheckUser and Mail::EXPN
405try to interact with the domain name system or particular
406mail servers to learn even more, but their methods do not
407work everywhere---especially for security conscious administrators.
408
409Many are tempted to try to eliminate many frequently-invalid
410mail addresses with a simple regex, such as
411C</^[\w.-]+\@(?:[\w-]+\.)+\w+$/>. It's a very bad idea. However,
412this also throws out many valid ones, and says nothing about
413potential deliverability, so it is not suggested. Instead, see
414http://www.cpan.org/authors/Tom_Christiansen/scripts/ckaddr.gz ,
415which actually checks against the full RFC spec (except for nested
416comments), looks for addresses you may not wish to accept mail to
417(say, Bill Clinton or your postmaster), and then makes sure that the
418hostname given can be looked up in the DNS MX records. It's not fast,
419but it works for what it tries to do.
420
421Our best advice for verifying a person's mail address is to have them
422enter their address twice, just as you normally do to change a password.
423This usually weeds out typos. If both versions match, send
424mail to that address with a personal message that looks somewhat like:
425
426 Dear [email protected],
427
428 Please confirm the mail address you gave us Wed May 6 09:38:41
429 MDT 1998 by replying to this message. Include the string
430 "Rumpelstiltskin" in that reply, but spelled in reverse; that is,
431 start with "Nik...". Once this is done, your confirmed address will
432 be entered into our records.
433
434If you get the message back and they've followed your directions,
435you can be reasonably assured that it's real.
436
437A related strategy that's less open to forgery is to give them a PIN
438(personal ID number). Record the address and PIN (best that it be a
439random one) for later processing. In the mail you send, ask them to
440include the PIN in their reply. But if it bounces, or the message is
441included via a "vacation" script, it'll be there anyway. So it's
442best to ask them to mail back a slight alteration of the PIN, such as
443with the characters reversed, one added or subtracted to each digit, etc.
444
445=head2 How do I decode a MIME/BASE64 string?
446
447The MIME-Base64 package (available from CPAN) handles this as well as
448the MIME/QP encoding. Decoding BASE64 becomes as simple as:
449
450 use MIME::Base64;
451 $decoded = decode_base64($encoded);
452
453The MIME-Tools package (available from CPAN) supports extraction with
454decoding of BASE64 encoded attachments and content directly from email
455messages.
456
457If the string to decode is short (less than 84 bytes long)
458a more direct approach is to use the unpack() function's "u"
459format after minor transliterations:
460
461 tr#A-Za-z0-9+/##cd; # remove non-base64 chars
462 tr#A-Za-z0-9+/# -_#; # convert to uuencoded format
463 $len = pack("c", 32 + 0.75*length); # compute length byte
464 print unpack("u", $len . $_); # uudecode and print
465
466=head2 How do I return the user's mail address?
467
468On systems that support getpwuid, the $< variable, and the
469Sys::Hostname module (which is part of the standard perl distribution),
470you can probably try using something like this:
471
472 use Sys::Hostname;
473 $address = sprintf('%s@%s', scalar getpwuid($<), hostname);
474
475Company policies on mail address can mean that this generates addresses
476that the company's mail system will not accept, so you should ask for
477users' mail addresses when this matters. Furthermore, not all systems
478on which Perl runs are so forthcoming with this information as is Unix.
479
480The Mail::Util module from CPAN (part of the MailTools package) provides a
481mailaddress() function that tries to guess the mail address of the user.
482It makes a more intelligent guess than the code above, using information
483given when the module was installed, but it could still be incorrect.
484Again, the best way is often just to ask the user.
485
486=head2 How do I send mail?
487
488Use the C<sendmail> program directly:
489
490 open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
491 or die "Can't fork for sendmail: $!\n";
492 print SENDMAIL <<"EOF";
493 From: User Originating Mail <me\@host>
494 To: Final Destination <you\@otherhost>
495 Subject: A relevant subject line
496
497 Body of the message goes here after the blank line
498 in as many lines as you like.
499 EOF
500 close(SENDMAIL) or warn "sendmail didn't close nicely";
501
502The B<-oi> option prevents sendmail from interpreting a line consisting
503of a single dot as "end of message". The B<-t> option says to use the
504headers to decide who to send the message to, and B<-odq> says to put
505the message into the queue. This last option means your message won't
506be immediately delivered, so leave it out if you want immediate
507delivery.
508
509Alternate, less convenient approaches include calling mail (sometimes
510called mailx) directly or simply opening up port 25 have having an
511intimate conversation between just you and the remote SMTP daemon,
512probably sendmail.
513
514Or you might be able use the CPAN module Mail::Mailer:
515
516 use Mail::Mailer;
517
518 $mailer = Mail::Mailer->new();
519 $mailer->open({ From => $from_address,
520 To => $to_address,
521 Subject => $subject,
522 })
523 or die "Can't open: $!\n";
524 print $mailer $body;
525 $mailer->close();
526
527The Mail::Internet module uses Net::SMTP which is less Unix-centric than
528Mail::Mailer, but less reliable. Avoid raw SMTP commands. There
529are many reasons to use a mail transport agent like sendmail. These
530include queuing, MX records, and security.
531
532=head2 How do I use MIME to make an attachment to a mail message?
533
534This answer is extracted directly from the MIME::Lite documentation.
535Create a multipart message (i.e., one with attachments).
536
537 use MIME::Lite;
538
539 ### Create a new multipart message:
540 $msg = MIME::Lite->new(
541 From =>'[email protected]',
542 To =>'[email protected]',
543 Cc =>'[email protected], [email protected]',
544 Subject =>'A message with 2 parts...',
545 Type =>'multipart/mixed'
546 );
547
548 ### Add parts (each "attach" has same arguments as "new"):
549 $msg->attach(Type =>'TEXT',
550 Data =>"Here's the GIF file you wanted"
551 );
552 $msg->attach(Type =>'image/gif',
553 Path =>'aaa000123.gif',
554 Filename =>'logo.gif'
555 );
556
557 $text = $msg->as_string;
558
559MIME::Lite also includes a method for sending these things.
560
561 $msg->send;
562
563This defaults to using L<sendmail> but can be customized to use
564SMTP via L<Net::SMTP>.
565
566=head2 How do I read mail?
567
568While you could use the Mail::Folder module from CPAN (part of the
569MailFolder package) or the Mail::Internet module from CPAN (part
570of the MailTools package), often a module is overkill. Here's a
571mail sorter.
572
573 #!/usr/bin/perl
574
575 my(@msgs, @sub);
576 my $msgno = -1;
577 $/ = ''; # paragraph reads
578 while (<>) {
579 if (/^From /m) {
580 /^Subject:\s*(?:Re:\s*)*(.*)/mi;
581 $sub[++$msgno] = lc($1) || '';
582 }
583 $msgs[$msgno] .= $_;
584 }
585 for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) {
586 print $msgs[$i];
587 }
588
589Or more succinctly,
590
591 #!/usr/bin/perl -n00
592 # bysub2 - awkish sort-by-subject
593 BEGIN { $msgno = -1 }
594 $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m;
595 $msg[$msgno] .= $_;
596 END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }
597
598=head2 How do I find out my hostname, domainname, or IP address?
599X<hostname, domainname, IP address, host, domain, hostfqdn, inet_ntoa,
600gethostbyname, Socket, Net::Domain, Sys::Hostname>
601
602(contributed by brian d foy)
603
604The Net::Domain module, which is part of the standard distribution starting
605in perl5.7.3, can get you the fully qualified domain name (FQDN), the host
606name, or the domain name.
607
608 use Net::Domain qw(hostname hostfqdn hostdomain);
609
610 my $host = hostfqdn();
611
612The C<Sys::Hostname> module, included in the standard distribution since
613perl5.6, can also get the hostname.
614
615 use Sys::Hostname;
616
617 $host = hostname();
618
619To get the IP address, you can use the C<gethostbyname> built-in function
620to turn the name into a number. To turn that number into the dotted octet
621form (a.b.c.d) that most people expect, use the C<inet_ntoa> function
622from the <Socket> module, which also comes with perl.
623
624 use Socket;
625
626 my $address = inet_ntoa(
627 scalar gethostbyname( $host || 'localhost' )
628 );
629
630=head2 How do I fetch a news article or the active newsgroups?
631
632Use the Net::NNTP or News::NNTPClient modules, both available from CPAN.
633This can make tasks like fetching the newsgroup list as simple as
634
635 perl -MNews::NNTPClient
636 -e 'print News::NNTPClient->new->list("newsgroups")'
637
638=head2 How do I fetch/put an FTP file?
639
640LWP::Simple (available from CPAN) can fetch but not put. Net::FTP (also
641available from CPAN) is more complex but can put as well as fetch.
642
643=head2 How can I do RPC in Perl?
644
645(Contributed by brian d foy)
646
647Use one of the RPC modules you can find on CPAN (
648http://search.cpan.org/search?query=RPC&mode=all ).
649
650=head1 AUTHOR AND COPYRIGHT
651
652Copyright (c) 1997-2006 Tom Christiansen, Nathan Torkington, and
653other authors as noted. All rights reserved.
654
655This documentation is free; you can redistribute it and/or modify it
656under the same terms as Perl itself.
657
658Irrespective of its distribution, all code examples in this file
659are hereby placed into the public domain. You are permitted and
660encouraged to use this code in your own programs for fun
661or for profit as you see fit. A simple comment in the code giving
662credit would be courteous but is not required.
Note: See TracBrowser for help on using the repository browser.