perlfaq9.pod

来自「视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.」· POD 代码 · 共 687 行 · 第 1/2 页

POD
687
字号
=head1 NAMEperlfaq9 - Networking ($Revision: 8539 $)=head1 DESCRIPTIONThis section deals with questions related to networking, the internet,and a few on the web.=head2 What is the correct form of response from a CGI script?(Alan Flavell <flavell+www@a5.ph.gla.ac.uk> answers...)The Common Gateway Interface (CGI) specifies a software interface betweena program ("CGI script") and a web server (HTTPD). It is not specificto Perl, and has its own FAQs and tutorials, and usenet group,comp.infosystems.www.authoring.cgiThe CGI specification is outlined in an informational RFC:http://www.ietf.org/rfc/rfc3875Other relevant documentation listed in: http://www.perl.org/CGI_MetaFAQ.htmlThese Perl FAQs very selectively cover some CGI issues. However, Perlprogrammers are strongly advised to use the CGI.pm module, to take careof the details for them.The similarity between CGI response headers (defined in the CGIspecification) and HTTP response headers (defined in the HTTPspecification, 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 serverdocumentation to see what it supports. "Parsed Header" scripts aresimpler in various respects. The CGI specification allows any of theusual newline representations in the CGI response (it's the server'sjob to create an accurate HTTP response based on it). So "\n" written intext mode is technically correct, and recommended. NPH scripts are moretricky: they must put out a complete and accurate set of HTTPtransaction response headers; the HTTP specification calls for recordsto be terminated with carriage-return and line-feed, i.e ASCII \015\012written in binary mode.Using CGI.pm gives excellent platform independence, including EBCDICsystems. CGI.pm selects an appropriate newline representation($CGI::CRLF) and sets binmode as appropriate.=head2 My CGI script runs from the command line but not the browser.  (500 Server Error)Several things could be wrong.  You can go through the "TroubleshootingPerl CGI scripts" guide at	http://www.perl.org/troubleshooting_CGI.htmlIf, after that, you can demonstrate that you've read the FAQs and thatyour problem isn't something simple that can be easily answered, you'llprobably receive a courteous and useful reply to your question if youpost it on comp.infosystems.www.authoring.cgi (if it's something to dowith HTTP or the CGI protocols).  Questions that appear to be Perlquestions but are really CGI ones that are posted to comp.lang.perl.miscare not so well received.The useful FAQs, related documents, and troubleshooting guides arelisted in the CGI Meta FAQ:	http://www.perl.org/CGI_MetaFAQ.html=head2 How can I get better error messages from a CGI program?Use the CGI::Carp module.  It replaces C<warn> and C<die>, plus thenormal Carp modules C<carp>, C<croak>, and C<confess> functions withmore verbose and safer versions.  It still sends them to the normalserver 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 modulewill try to take care of this to avoid the dreaded server 500 errors.Normal warnings still go out to the server error log (or whereveryou've sent them with C<carpout>) with the application name and datestamp prepended.=head2 How do I remove HTML from a string?The most correct way (albeit not the fastest) is to use HTML::Parserfrom CPAN.  Another mostly correctway is to use HTML::FormatText which not only removes HTML but alsoattempts to do a little simple formatting of the resulting plain text.Many folks attempt a simple-minded regular expression approach, likeC<< s/<.*?>//g >>, but that fails in many cases because the tagsmay continue over line breaks, they may contain quoted angle-brackets,or HTML comment may be present.  Plus, folks forget to convertentities--like C<&lt;> for example.Here's one "simple-minded" approach, that works for most files:    #!/usr/bin/perl -p0777    s/<(?:[^>'"]*|(['"]).*?\1)*>//gsIf you want a more complete solution, see the 3-stage striphtmlprogram inhttp://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz.Here are some tricky cases that you should think about when pickinga 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 breakon text like this:    <!-- This section commented out.        <B>You can't see me!</B>    -->=head2 How do I extract URLs?You can easily extract all sorts of URLs from HTML withC<HTML::SimpleLinkExtor> which handles anchors, images, objects,frames, and many other tags that can contain a URL.  If you needanything more complex, you can create your own subclass ofC<HTML::LinkExtor> or C<HTML::Parser>.  You might even useC<HTML::SimpleLinkExtor> as an example for something specificallysuited to your needs.You can use URI::Find to extract URLs from an arbitrary text document.Less complete solutions involving regular expressions can saveyou a lot of processing time if you know that the input is simple.  Onesolution from Tom Christiansen runs 100 times faster than mostmodule based approaches but only extracts URLs from anchors where the firstattribute is HREF and there are no other attributes.        #!/usr/bin/perl -n00        # qxurl - tchrist@perl.com        print "$2\n" while m{            < \s*              A \s+ HREF \s* = \s* (["']) (.*?) \1            \s* >        }gsix;=head2 How do I download a file from the user's machine?  How do I open a file on another machine?In this case, download means to use the file upload feature of HTMLforms.  You allow the web surfer to specify a file to send to your webserver.  To you it looks like a download, and to the user it lookslike an upload.  No matter what you call it, you do it with what'sknown as B<multipart/form-data> encoding.  The CGI.pm module (whichcomes with Perl as part of the Standard Library) supports this in thestart_multipart_form() method, which isn't the same as the startform()method.See the section in the CGI.pm documentation on file uploads for codeexamples and details.=head2 How do I make an HTML pop-up menu with Perl?(contributed by brian d foy)The CGI.pm module (which comes with Perl) has functions to createthe HTML form widgets. See the CGI.pm documentation for moreexamples.	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;=head2 How do I fetch an HTML file?One approach, if you have the lynx text-based HTML browser installedon 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 wayto do this.  They don't require lynx, but like lynx, can still workthrough proxies:    # simplest version    use LWP::Simple;    $content = get($URL);    # or print HTML from a URL    use LWP::Simple;    getprint "http://www.linpro.no/lwp/";    # or print ASCII from HTML from a URL    # also need HTML-Tree package from CPAN    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;=head2 How do I automate an HTML form submission?If you are doing something complex, such as moving through many pagesand forms or a web site, you can use C<WWW::Mechanize>.  See itsdocumentation for all the details.If you're submitting values using the GET method, create a URL and encodethe form using the C<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 encodethe 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;=head2 How do I decode or create those %-encodings on the web?If you are writing a CGI script, you should be using the CGI.pm modulethat comes with perl, or some other equivalent module.  The CGI moduleautomatically 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;   # encode    s/%([A-Fa-f\d]{2})/chr hex $1/eg;                # decode	s/%([[:xdigit:]]{2})/chr hex $1/eg;          # same thingHowever, you should only apply them to individual URI components, notthe entire URI, otherwise you'll lose information and generally messthings up.  If that didn't explain it, don't worry.  Just go readsection 2 of the RFC, it's probably the best explanation there is.RFC 2396 also contains a lot of other useful information, including aregexp for breaking any arbitrary URI into components (Appendix B).=head2 How do I redirect to another page?Specify the complete URL of the destination (even if it is on the sameserver). This is one of the two different kinds of CGI "Location:"responses which are defined in the CGI specification for a Parsed Headersscript. The other kind (an absolute URLpath) is resolved internally tothe server without any HTTP redirection. The CGI specifications do notallow relative URLs in either case.Use of CGI.pm is strongly recommended.  This example shows redirectionwith 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.  Thisredirection 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" isshown separately, for clarity), using either a complete URL oran absolute URLpath.      print "Location: $url\n";   # CGI response header      print "\n";                 # end of headers=head2 How do I put a password on my web pages?To enable authentication for your web server, you need to configureyour web server.  The configuration is different for different sortsof web servers--apache does it differently from iPlanet which doesit differently from IIS.  Check your web server documentation forthe details for your particular server.=head2 How do I edit my .htpasswd and .htgroup files with Perl?The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide aconsistent OO interface to these files, regardless of how they'restored.  Databases may be text, dbm, Berkeley DB or any database witha DBI compatible driver.  HTTPD::UserAdmin supports files used by the"Basic" and "Digest" authentication schemes.  Here's an example:    use HTTPD::UserAdmin ();

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?