DBX has asked for the wisdom of the Perl Monks concerning the following question:

I'm curious what fellow monks think is the best way for a script to know if it's running as a cgi? I usually test for things like:
$ENV{REMOTE_ADDR} or $ENV{HTTP_HOST} or $ENV{HTTP_USER_AGENT}
but there might be a better way...?

Replies are listed 'Best First'.
(crazyinsomniac) Re: How can a script know if it's a cgi?
by crazyinsomniac (Prior) on Aug 24, 2001 at 11:23 UTC
    Practically, checking %ENV for certain common CGI variables will rarely steer you wrong, butt, -t is what you want. From pod (my favorite literature):

    perlfunc: -t Filehandle is opened to a tty. #(STDIN by default)

    perlfaq8:

    How do I find out if I'm running interactively or not? Good question. Sometimes -t STDIN and -t STDOUT can give clues, someti +mes not. if (-t STDIN && -t STDOUT) { print "Now what? "; } On POSIX systems, you can test whether your own process group matches +the current process group of your controlling terminal as follows: use POSIX qw/getpgrp tcgetpgrp/; open(TTY, "/dev/tty") or die $!; $tpgrp = tcgetpgrp(fileno(*TTY)); $pgrp = getpgrp(); if ($tpgrp == $pgrp) { print "foreground\n"; } else { print "background\n"; }
    and even perlsyn:
    $on_a_tty = -t STDIN && -t STDOUT; sub prompt { print "yes? " if $on_a_tty } for ( prompt(); <STDIN>; prompt() ) { # do something }

     
    ___crazyinsomniac_______________________________________
    Disclaimer: Don't blame. It came from inside the void

    perl -e "$q=$_;map({chr unpack qq;H*;,$_}split(q;;,q*H*));print;$q/$q;"

Re: How can a script know if it's a cgi?
by Cine (Friar) on Aug 24, 2001 at 03:48 UTC
    Check this site where you can see which enviroment variables are set.

    T I M T O W T D I
Re: How can a script know if it's a cgi?
by blakem (Monsignor) on Aug 24, 2001 at 03:47 UTC
    It depends on your server environment... how are the CGIs being invoked?

    You could check $ENV{GATEWAY_INTERFACE}, though it might be a mod_perl only thing. (haven't written straight CGI in a while...) This code is invoked before any of my mod_perl scripts are run.

    # make sure we are in a sane environment. $ENV{GATEWAY_INTERFACE} =~ /^CGI-Perl/ or die "GATEWAY_INTERFACE not P +erl!";

    You could compare dumps of the %ENV hash, when invoked from the command line vs. CGI. Something like:

    print "$_ => $ENV{$_}<BR>\n" for (keys %ENV);

    -Blake