且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何确定Perl脚本是否在CGI上下文中执行?

更新时间:2023-12-04 21:36:46

***的选择是检查 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'};