Search code examples
perlfastcgi

Perl how to detect if running under Fast CGI FCGI


How to detect inside Perl script if it is called under FCGI or CGI. I want to detect if running under FCGI then load the FCGI modules, something like this at the top of the script:

if ($ENV{FCGI}) {
    use FCGI;
    use MyFCGIHandler;
}

I know I can do something like this:

use FCGI;
my $request = FCGI::Request();

#Returns whether or not the program was run as a FastCGI.
$isfcgi = $req->IsFastCGI();

But this means I have to load the FCGI module and call its Request and isFastCGI methods to check which is not good if app is not running under FCGI.


Solution

  • Found this at PerlMonks:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use CGI::Fast qw(:standard);
    
    sub mode
    {
            my $h=$CGI::Fast::Ext_Request;
            if (defined($h) && ref($h) && $h->IsFastCGI()) {
                    return 'FastCGI';
            } else {
                    return 'CGI';
            }
    }
    
    while (CGI::Fast->new()) {
            print
                    header(),
                    start_html('CGI or FastCGI?'),
                    h1('CGI or FastCGI?'),
                    p('This application runs in ',mode(),' mode.'),
                    end_html();
    }