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

心已入冬 提交于 2019-12-19 06:03:36

问题


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?


回答1:


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



回答2:


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";



回答3:


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



回答4:


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

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


来源:https://stackoverflow.com/questions/4853948/how-can-i-tell-if-a-perl-script-is-executing-in-cgi-context

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!