开发者

How can I tell if a Perl script is executing in CGI context?

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?


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'};

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'};


You would best check the GI in the CGI.

use CGI qw( header );

my $is_cgi = defined $ENV{'GATEWAY_INTERFACE'};

print header("text/plain") if $is_cgi;
print "O HAI, ", $is_cgi ? "CGI\n" : "COMMAND LINE\n";


One possible way is to check environment variables that are set by web servers.

#!/usr/bin/perl

use strict;
use warnings;

our $IS_CGI = exists $ENV{'HTTP_HOST'};


See if your program is connected to a TTY or not:

my $where = -t() ? 'command line' : 'web server';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜