10

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?

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
ryeguy
  • 65,519
  • 58
  • 198
  • 260
  • 1
    http://stackoverflow.com/questions/1914966/how-can-i-determine-if-a-script-was-called-from-the-command-line-or-as-a-cgi-scri http://stackoverflow.com/questions/3086655/in-perl-how-to-distiniguish-between-cli-cgi-mode – daxim Jan 31 '11 at 20:00
  • Possible duplicate of [How to distinguish between CLI & CGI modes in Perl](https://stackoverflow.com/questions/3086655/how-to-distinguish-between-cli-cgi-modes-in-perl) – Ωmega Sep 11 '19 at 16:16

4 Answers4

16

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'};
Ven'Tatsu
  • 3,565
  • 16
  • 18
6

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";
Ashley
  • 4,307
  • 2
  • 19
  • 28
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'};
Tony Miller
  • 9,059
  • 2
  • 27
  • 46
-1

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

my $where = -t() ? 'command line' : 'web server';
tadmc
  • 3,714
  • 16
  • 14
  • 5
    -1: Incorrect. This will tell you whether the program is running interactively, not whether it's running under CGI. Being called from a cron job or as part of a shell pipeline would give incorrect results (it would be non-interactive, but also non-CGI). – Dave Sherohman Feb 01 '11 at 10:28