Integrating Perl with PHP in Windows

erl is a script programming language that has a syntax similar to C. It includes a number of popular Unix facilities such as SED, awk, and tr. Perl comes pre-installed on Linux machines, but to use Perl in Windows, you must download and install some programs that allow you to execute Perl scripts from a command prompt. Perl is a general-purpose language often used for applications that require database access, graphics programming, network programming, and CGI programming on the Web.

This article demonstrates how to:

  • Install and configure Perl for Windows using the free ActivePerl distribution and Cygwin, the Unix-like environment
  • Execute Perl scripts using PHP
  • Send different types of arguments to a Perl script
  • Use Perl recursive functions from PHP
  • Generate HTML files
  • Pass arrays from PHP to Perl and vice-versa
  • Pass object members from PHP to a Perl script

Download and Configure ActivePerl for Windows

ActivePerl is a free Perl distribution for Windows created by the ActiveState software company that comes pre-configured and ready to install. First, download ActivePerl, and then follow the installation wizard’s directions to create a ready-to-use Perl installation.

To test a Perl script, open an MS-DOS command prompt and navigate to your Perl installation folder, then type:

>perl ${PATH_TO_SCRIPT}/test.pl   

Here’s a simple one-line test Perl (test.pl) script:

print "Hello from ActivePerl!
";
Author’s Note: Perl files have a .pl extension by default, but you can also create and use Perl scripts with a .txt extension.

 
Figure 1. Testing Perl : When you run the one-line test Perl script, you should see this output.

When you run the script, it should output “Hello from ActivePerl!” (see Figure 1); if that happens, then the script executed successfully.

With Perl running, the next step is to add PHP into the equation.

Calling Perl Scripts from PHP

To execute Perl scripts from PHP, you use the shell_exec function, which has the following prototype:

string shell_exec ( string $cmd )

This executes a command using the command shell, and returns the output as a string. The $cmd parameter represents the command to be executed.

Author’s Note: The shell_exec function is disabled when PHP is running in safe mode.

Here’s an example that calls a Perl script from PHP. The Perl script is the test.pl example you created earlier; the PHP application that calls the Perl script is test.php. You can find all the example scripts in the downloadable code for this article.

Save the file as test.php, and open it in a browser, and you should see the “Hello from ActivePerl!” message appear on the page.

Of course, you often want to pass data to a script, and get results back. This next PHP script passes two integers and a float (144, 22 and 34.3445) to a Perl script, which uses the values to do some mathematical calculations (sum, average, square root and more) and prints the results. Here’s the PHP script (values.php):

The preceding code calls the values.pl Perl script that does the actual work. Here’s the code:

# Parameters sent by the PHP script$a=$ARGV[0];$b=$ARGV[1];$c=$ARGV[2];print "The three parameters passed by the PHP script are:  ";print $a." --- ".$b." --- ".$c."
";#Exercise some of the Perl math functions #using the three parameters $a,$b,$cprint "sum(a+b) =";print $a+$b."
";print "product(a*b) = ";print $a*$b."
";print "average(a,b,c) = ";print (($a+$b+$c)/3);print "
";print "sqrt(a) = ";print sqrt($a)."
";print "int(c) = ";print int($c)."
";print "log(a) = ";print log($a)."
";
The output is:The three parameters passed by the PHP script are: 144 --- 22 --- 34.3445sum(a+b) =166product(a*b) = 3168average(a,b,c) = 66.7815sqrt(a) = 12int(c) = 34log(a) = 4.969813299576
Author’s Note: You can send countless arguments from PHP to a Perl script. Perl will extract them using positional arguments ($ARGV[0],$ARGV[1]…, $ARGV[n]). The preceding example assigns values to $a, $b, and $c in that manner: $ARGV[0]=144, $ARGV[1]=22 and $ARGV[2]=34.3445.

Even in this simple math example, you can see how the Perl script generated some standard line break HTML tags (
) to format the output. It’s worth taking that a step further, because you can use Perl scripts to generate more complex formatting.

PHP, HTML and Perl

This application generates a simple HTML document using a Perl script called from PHP. Here are the PHP (perlPHP.php) and the Perl scripts (perlHTML.pl) used to generate the HTML code:

Listing perlHTML.pl:# output some html codeprint "";print "Perl -HTML";print "";print "

This page comes from Perl

";print "Hello Everybody!";print "";print "";

The output that appears in browser should be formatted text, as shown below, between the horizontal rules:


This page comes from Perl

Hello Everybody!


Calling a Single Function in a Perl Script

You can create subroutines in Perl using the sub control structure, and then call them many times, just like any other built-in Perl functions (such as print, join, sort etc.). Here’s the general syntax of the sub command:

sub mysub {   instruction1;   instruction2;   ...   instruction3;}

As an example, this next application uses a recursive function to calculate the sum of the first 65 consecutive integer numbers. The Perl script (function.pl) contains a recursive function, sum:

#Argument from the PHP script#in this case the argument=65 #and is used to call the recursive function sum$a=$ARGV[0];#Calling the recursive function sum$var = sum($a);#Listing the result after the sum function was executedprint "Sum of 1+2+3+...+$a numbers is = $var
";  # Define the recursive function sub sum{  my $num = $_[0]; # Declaring local variable    if ( $num == 0 )      {       $var = 0;        return ;       }else{       # The recursive expression       $var = $num + sum($num-1);        }}

Here’s the function.php PHP script that calls the Perl sum function:

The output is:

Sum of 1+2+3+...+65 numbers is = 2145
Author’s Note: Note that the PHP script calls the Perl script, not the Perl function itself. The Perl script calls the recursive function internally.

Calling Individual Functions in a Multi-Function Script

When you have more than one function in the Perl script, you have to use a trick to call the one you want.

For example, suppose you have a Perl script (functionsCall.pl) that contains two functions. The first function calculates the factorial of a given number, and the second one is the recursive sum function from the previous section as shown in Listing 1.

Now suppose you want to call only one of the functions in Listing 1. To do that, you must write the Perl script so it can selectively execute a function name and pass the arguments. The following PHP example (functionsCall.php) calls the Perl function fact (from Listing 1), passing the argument 12:

The output is:

The function -- fact -- was called from PHP and the fact(12) is : 479001600 

To call the sum function with the argument 39 instead, all you need to do is replace the calling line in the PHP script:

$result=shell_exec(   "C:Perlinperl.exe functionsCall.pl sum 39");

This time, the result is:

The function -- sum -- was called from PHP and the sum of the first 39 numbers is 780

Passing Arrays Between PHP and Perl

In Perl, an array is a data type that stores a list of data types. Each element of the array can be a string, a number or any type of scalar data, including another variable. Perl numbers array elements starting from zero. Here’s how you declare an array in Perl:

@arrayname = ("element1", "element2",…,"elementn"); 

Array names must begin with an @ symbol, and there is no maximum limit on the size of an array. You can reference any element of an array using the syntax @arrayname[subscript].

The next example passes a set of strings as an argument to a Perl script, which groups them into an array. The following example (array.php) sends three strings:

The array.pl Perl script (see Listing 2), performs some basic Perl string operations: adding elements, removing elements, transforming arrays into strings and vice-versa, and sorting the array:

When you brows to the array.php page, you’ll see output that looks like this:

The Perl array is : Mark Jane Martin Print each element of the array : MarkJaneMartinAdding one element at the end : Mark Jane Martin MaryAdding one element at the beginning : Tom Mark Jane Martin MaryRemove the last element of the array : Tom Mark Jane MartinTransforming the array into a string : Tom:Mark:Jane:MartinTransforming the string into array : Tom Mark Jane MartinSorting the array : Jane Mark Martin Tom

To pass a PHP array to Perl (instead of a list of arguments), first convert the PHP array into a delimited string and pass it as shown below in the arraytoString.php script (you can use any separator character—this example uses a colon):

';echo $separated."
";//Execute the arraytostring.pl Perl script$result=shell_exec("C:Perlinperl.exe arraytoString.pl ".$separated.' " ');?>

The following arraytoString.pl Perl script builds an array from the delimited string argument:

#print "Hello from ActivePerl!
";$PHPstring=$ARGV[0];#Convert the string into a Perl [email protected]= split(/:/, $PHPstring);#Display the array#print "The Perl array is : @token 
";#Convert the token array into a string$Perlstring = join('//',@token);print "$Perlstring";
Author’s Note: The preceding Perl script appends the string “Perl “ to every array element as a flag to show that the Perl script worked.

You could return the joined string to PHP, and then reconstruct the array from the delimited Perl string:

//Convert from Perl string to PHP array$pieces = explode("//", $result);      //Listing the PHP arrayecho "

Convert from Perl string to PHP array:
";echo "pieces[0]=".$pieces[0]."Perl
"; echo "pieces[1]=".$pieces[1]."Perl
"; echo "pieces[2]=".$pieces[2]."Perl
"; echo "pieces[3]=".$pieces[3]."Perl
"; echo "pieces[4]=".$pieces[4]."Perl
"; ?>

The script uses the explode method to convert the delimted string into a PHP array. The output is:

Convert from Perl string to PHP array: pieces[0]=onePerl  pieces[1]=twoPerl pieces[2]=threePerl pieces[3]=fourPerl pieces[4]=fivePerl 

Object-Oriented Perl

Objects are collections of data (properties), and code (methods). A Perl class is syntactically identical to a C struct, and is a simply a package that provides methods to deal with objects. A method is simply a subroutine that expects an object reference as its first argument.

Here’s an application that creates a simple Perl class, instantiates it, serializes it, and writes the serialized object into a text file (file.txt). The PHP script reads the file.txt file to de-serialize the Perl object, and prints the result. To use the Perl serialize and unserialize functions, you must instal the PHP::Serialization Perl module, which you can download. Save the downloaded PHP-Serialization-0.27/lib/PHP/Serialization.pm file to your PHP directory. To use the PHP::Serialization module from the example oop.pl Perl script, add this line to the beginning of the script:

use PHP::Serialization;

The oop.php PHP script that executes the Perl script is:

And the Perl script that creates the Perl class serializes it to file.txt is:

use PHP::Serialization;package Cars;sub new{    my $class = shift;    my $self = {        _Model => shift,        _Color  => shift,        _Series => shift,        };        bless $self;    return $self;}#instantiating the Cars class$object = new Cars( "Ferrari", "red", 898766);#Listing the object’s properties #print "The car model is: $object->{_Model} 
";#print "The car color is: $object->{_Color}
";#print "The car series is: $object->{_Series}
";#serialize the $object variable$var = PHP::Serialization::serialize($object);#Write the serialized result into file.txt open (DATA, ">file.txt");print DATA "$var";close(DATA);

After the script runs, the file.txt file containing the serialized object in PHP style is:

O:4:"Cars":3:{s:6:"_Series";i:898766;s:6:   "_Color";s:3:"red";s:6:"_Model";s:7:"Ferrari";}

Finally, the output is:

__PHP_Incomplete_Class Object (    [__PHP_Incomplete_Class_Name] => Cars    [_Series] => 898766    [_Color] => red    [_Model] => Ferrari )

Passing PHP Object Members to Perl

Suppose you have an instance of a PHP class named SimpleClass, and you want to pass that object’s members to a Perl script. Here’s the SimpleClass definition:

displayVar();?>

Using the serialize methods introduced in the preceding example, you can then serialize an instance of the SimpleClass, and pass the serialized result to Perl as shown below (obviously, the Perl script must implement a de-serialize mechanism to extract the member’s names and values):

...echo "Perl call ...
";//Serializing the object$var = serialize($simpleClass);$result=shell_exec(   "C:Perlinperl.exe serialize.pl $var");echo($result);...

The serialize.pl Perl script called by the preceding code is:

$var = $ARGV[0];print "$var";

Alternatively, you can pass class members explicitly. This objectPerl.php script shows how:

displayVar();echo "Perl  call ...
";$cmd = "C:Perlinperl.exe objectPerl.pl $simpleClass->name $simpleClass->surname $simpleClass->phone";$result = shell_exec($cmd);echo($result);?>

When passing instance members explicitly passing, the receiving objectPerl.pl Perl script would look like this:

print "The name is: ".$ARGV[0];print "
The surname is: ".$ARGV[1];print "
The phone number is: ".$ARGV[2];

The output is:

Perl call ...The Name is: ElThe Surname is: RamonThe phone number is: 3274927349

Using Cygwin

Cygwin is a tool that lets you to use a Linux environment on Windows systems. Cygwin contains a DLL (cygwin1.dll) that acts as a Linux API emulation layer. It provides substantial Linux API functionality and a collection of tools with the Linux “look and feel,” all of which conform to the official Linux specification.

You can download Cygwin from http://www.cygwin.com. The download includes a setup.exe file that will guide you through the install process. After you select and install all the Cygwin packages you need, run Cygwin at the command prompt by double-clicking on the Cygwin.bat file. You’ll see the screen in Figure 2.

 
Figure 2. The Cygwin Command Prompt: Running Cygwin using the cygwin.bat file produces a Cygwin command prompt.

You can use Cygwin to run shell command scripts, to login remotely to any PC, and to fix problems within a Posize/Linux/UNIX shell on any Windows machine. To use Cygwin into your PHP applications all you need to do is set the path to the Perl.exe file like this:

${CYGWIN_HOME}inPerl.exe

Therefore, to run a PHP script that will execute a Perl script through Cygwin you would write:

You can replace Perl_script_name with any of the Perl scripts available in the downloadable code for this article.

At this point, you’re seen a suite of examples focused on calling Perl from PHP, and you should be comfortable with calling Perl scripts from PHP using various argument types (strings, numbers, arrays, and objects) and with calling specific subroutines in Perl scripts.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: