Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if a script was called from the command line or as a cgi script?

I have a script that I wrote that can either be used on the command line or as a CGI script, and need to determine how the script was called so I can output a content-type header for web requests (and maybe some anti-cache headers too). My first thought is to check for the existance of http environment variables:

my $js = build_javascript();

if ( exists $ENV{HTTP_HOST} ) {
   print "Content-type: text/javascript\n\n";
}
print $js;

Is there a better way?

like image 563
Stephen Sorensen Avatar asked Dec 16 '09 14:12

Stephen Sorensen


3 Answers

According to the CGI specification in RFC3875 (section 4.1.4.), the GATEWAY_INTERFACE environment variable would be the authoritative thing to check whether you are running in a CGI context:

4.1.4. GATEWAY_INTERFACE

The GATEWAY_INTERFACE variable MUST be set to the dialect of CGI being used by the server to communicate with the script.

like image 140
VoidPointer Avatar answered Sep 21 '22 14:09

VoidPointer


There's really no way good way to tell if your script was started by a web server or from the command line. Any of the environment variables can be set in both situations. I often run CGI programs straight from the command line to test them, for instance.

Knowing that, if you want to pick one environment variable to use, it just has to be one that you won't set in the other situation, or one that you set in both but give different values to. In that case, choose any environment variable that you like.

If you want to get more sophisicated, you can use something like IO::Interactive to determine if you're connected to a terminal. If you aren't, the filehanandle that is_interactive returns is a null filehandle and the output goes nowhere:

 print { is_interactive() } $http_header;

If you don't like how IO::Interactive decides, you can reimplement is_interactive. It's a very short piece of code and the higher-level interface is very nice.

like image 20
brian d foy Avatar answered Sep 21 '22 14:09

brian d foy


I usually do a little trick at the beginning of my module:

exit run(@ARGV) unless caller();   # run directly if called from command line

sub run
{
    process_options(@_);
    ...
}

sub process_options {
    @ARGV = @_;
    my  %opts;
    GetOptions(\%opts,
    ...
}

The module does not have to be named "run".

like image 27
Peter Avatar answered Sep 21 '22 14:09

Peter