如何确定Perl脚本是否在CGI上下文中执行? [英] How can I tell if a Perl script is executing in CGI context?
问题描述
我有一个Perl脚本,它将从命令行作为CGI运行。在Perl脚本中,如何确定其运行方式?
I have a Perl script that will be run from the command line and as CGI. From within the Perl script, how can I tell how its being run?
推荐答案
最好的选择是检查 GATEWAY_INTERFACE
环境变量。它将包含服务器使用的CGI协议版本,几乎始终是 CGI / 1.1
。 Tony Miller提到的 HTTP_HOST
变量(或任何 HTTP _ *
变量)仅在客户端提供时设置。客户端省略 Host
标头的情况很少见,但并非并非不可能,而未设置 HTTP_HOST
不变。
The best choice is to check the GATEWAY_INTERFACE
environment variable. It will contain the version of the CGI protocol the server is using, this is almost always CGI/1.1
. The HTTP_HOST
variable mentioned by Tony Miller (or any HTTP_*
variable) is only set if the client supplies it. It's rare but not impossible for a client to omit the Host
header leaving HTTP_HOST
unset.
#!/usr/bin/perl
use strict;
use warnings;
use constant IS_CGI => exists $ENV{'GATEWAY_INTERFACE'};
如果我期望在mod_perl下运行,我还将检查 MOD_PERL
环境变量也是如此,因为它将在首次编译脚本时设置。
If I'm expecting to run under mod_perl at some point I'll also check the MOD_PERL
environment variable also, since it will be set when the script is first compiled.
#!/usr/bin/perl
use strict;
use warnings;
use constant IS_MOD_PERL => exists $ENV{'MOD_PERL'};
use constant IS_CGI => IS_MOD_PERL || exists $ENV{'GATEWAY_INTERFACE'};
这篇关于如何确定Perl脚本是否在CGI上下文中执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!