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?
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.
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.
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!\
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";
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'};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With