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?
10
votes
4 Answers
16
votes
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'};
6
votes
3
votes