Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a Perl script is executing in CGI context?

Tags:

cgi

perl

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?

like image 609
ryeguy Avatar asked Jan 31 '11 17:01

ryeguy


People also ask

How does Perl CGI work?

In Perl, CGI(Common Gateway Interface) is a protocol for executing scripts via web requests. It is a set of rules and standards that define how the information is exchanged between the web server and custom scripts. Earlier, scripting languages like Perl were used for writing the CGI applications.

Is Perl CGI server side or client side?

CGI refers to server-side execution, while Java refers to client-side execution. There are certain things (like animations) that can be improved by using Java. However, you can continue to use Perl to develop server-side applications.

How do I run Perl CGI script in Windows?

Enter this test Perl CGI script, hello_CGI.pl, with a text editor. Note that the first line must specify correctly where the perl.exe is installed. #!/local/perl/bin/perl.exe print "Content-Type: text/html\n\n"; print "<html><body>\n"; print "Hello world!\


2 Answers

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";
like image 84
Ashley Avatar answered Oct 28 '22 11:10

Ashley


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'};
like image 26
Ven'Tatsu Avatar answered Oct 28 '22 13:10

Ven'Tatsu