How to determine if a script is called from the command line or how is a cgi script?

I have a script that I wrote that can be used on the command line or as a CGI script, and I need to determine how the script was called, so I can output a content type header for web requests (and maybe some anti caches). My first thought is to check for 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?

+7
command-line perl environment-variables cgi
source share
3 answers

According to the CGI specification in RFC3875 (section 4.1.4.), The GATEWAY_INTERFACE environment variable would be an authoritative thing to check whether you work in the context of CGI:

4.1.4. GATEWAY_INTERFACE

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

+18
source share

There really is no good way to find out if your script was launched by the web server or from the command line. Any of the environment variables can be set in both situations. I often run CGI programs directly from the command line to test them, for example.

Knowing that if you want to select one environment variable to use, it just needs to be one that you do not specify in another situation, or one that you set in both, but give different values. In this case, select any environment variable that you like.

If you want more features, you can use something like IO :: Interactive to determine if you are connected to the terminal. If you haven’t done so, the filehanandle that returns is_interactive is the null file descriptor, and the output does not go anywhere:

  print { is_interactive() } $http_header; 

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

+8
source share

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 should not be called "run".

+2
source share

All Articles