#nginx

How to run perl from index.php

Sometimes you need to run a simple perl script, but your webhosting is configured to look for index.php only. Here is the way to get it through:

Edit index.php

<?php
foreach ($_SERVER as $key => $value) { putenv("$key=$value"); }
foreach ($_GET as $key => $value)    { putenv("GET_$key=".escapeshellarg($value)); }
foreach ($_POST as $key => $value)   { putenv("POST_$key=".escapeshellarg($value)); }

echo shell_exec('perl index.pl 2>&1');

Create your index.pl

#!/usr/bin/perl

use Data::Dumper; $Data::Dumper::Sortkeys = 1;

print "Done.\n";

print Dumper( \@INC );
print Dumper( \%ENV );

Conclusion

All $_GET variables will be in GET_xxx environment variables.

All $_POST variables will be in POST_xxx environment variables.

ALL $_SERVER variables will be set as CGI environment variables.

This is 'out of head' document. It should be tested.

That's all.

How to use perl script with nginx

Sometimes you need to run a simple perl script, without a need to create a full perl web app. The easiest way is to use it using nginx+fcgiwrapper.

Install required software

apt intall nginx
apt install fcgiwrap

Configure nginx

/etc/nginx/sites-enabled/test.com.conf

location ~ \.pl$ {
  try_files $uri =404; # without this, we will get '403 Forbidden'
  fastcgi_param SCRIPT_NAME $fastcgi_script_name;
  fastcgi_pass unix:/var/run/fcgiwrap.socket;
  include fastcgi_params;

  # run it immediately, without buffering ....
  fastcgi_param NO_BUFFERING "1";
  fastcgi_keep_conn on;
}

Note:

Files .pl MUST BE in the path accessible by the nginx.

Buffering is active per-default. With current installation on Ubuntu, there is no way to disable buffering and enable streaming.

Example:

#!/usr/bin/perl

use strict;
use warnings;

# To enable buffering:
$|=1;
# tell browser, not to wait for content...
print "Content-Encoding: none\n";
print "Content-Type: text/html; charset=ISO-8859-1;\n";
print "\n\n";

print "<h1>Perl is working!</h1>\n";
sleep 1;
print "test2<br>\n";
sleep 2;
print "test3<br>\n";
sleep 3;
print "test4<br>\n";

Tested on:

  • system1:

    Ubuntu 20.04.1 LTS

    apt show fcgiwrap

    Version: 1.1.0-12

All Articles Bookmarks