Integrating PHP and Perl

PHP and Perl are both so powerful, they can even run each other.
Setting Up PHP::Interpreter

Setting up PHP::Interpreter is basically a standard Perl module installation procedure. You can get it from Unpack it, and create the Makefile:

perl Makefile.PL

Compile it:


And, install it:

make install

You can do an additional:

pod2html > interpreter.html

and keep the documentation file for future reference.

We also use the CPAN module File::Tail, which allows us to monitor a log file continuously. You can get this module from

Unpack it, and create the Makefile:

perl MakeFile.PL
make install

Now, fire up a text editor, and start coding:

1. use PHP::Interpreter;
2. use File::Tail;
3. use threads ('yield', 'stack_size' =>64 * 4096, 'exit'
4. use Thread;
5. my $php = PHP::Interpreter->new;
6. my $ref=tie *FH,"File::Tail",(name=>'/var/log/messages');
7. while (<FH>)
8. {
9. if($_=~/sshd/) #checks for message from sshd
10. {
11. if($_=!/Failed password for/) #check for a failed password attempt
12. {
13. $ind = rindex($str,'from');
14. $rind = rindex($str,'port');
15. $ip = substr($str,$ind+4,$rind-$ind-4);
16. $thr = new Thread \&writems, $ip;
17. $thr->join();
18. }
19. }
20. }
21. sub writems
22. {
23. `iptables -I INPUT -s $ip -j DROP`
24. $php->include(*"*writems.php*"*);
25. $php->writeIP('ssqlserver','sshwatch','sshusr','sshpass',$_[0]);
26. print $php->eval("echo Succeeded!");
27. }

In a separate file, write the following script (the file should be named writems.php):

1. <?php
2. function writeIP($dbhost,$dbname,$dbuser,$dbpass,$ip)
3. {
4. $conn = mssql_connect($dbhost,$dbuser,$dbpass)
5. or die("Couldn't connect to SQL Server on $dbhost");
6. $db = mssql_select_db($dbname, $s)
7. or die("Couldn't open database $myDB");
8. set_time_limit(0);
9. $squery="insert into sshwatch(currentdate,ip)
10. values('".date('Y/m/d')."','".$ip."')"; mssql_query($squery);
11. }
12. ?>

To run the application, simply run the Perl script:

Perl scriptname

In Line 25, you need to fill in the correct settings for your MSSQL server installation. You also need to have a PHP installation with support for MSSQL. This is usually done by passing the switch -with-mssql during the compilation of PHP. Some distributions also require you to install FreeTDS, which is used by PHP to access MSSQL.

Now, let's review some specific portions of the code. To use the PHP::Interpreter in your code, declare its use, as in line 1. To create a new instance of PHP interpreter, do as is shown in line 5:

my $php = PHP::Interpreter->new;

As with object-oriented programming, you now can invoke methods on the $php object to achieve interoperability with PHP. The above code shows two functions provided by the PHP::Interpreter for interoperability. In line 24, we are calling the include() function, which includes a PHP script file to the environment, and you can call functions defined in the file natively from the object. We do the same with writeIP in line 25, which is a PHP function declared in writems.php on line 2 of the writems.php listing. The Eval function of the $php object allows you to execute a specific PHP instruction, as with a live interpreter. The instruction is interpreted, and the return may be stored into a variable or used directly, as in line 26. As you can see in the above program, PHP::Interpreter provides an object-oriented mechanism for completely integrating the two languages. This integration is achieved with only two lines of code: the initial use statement and the instantiation of the object. PHP::Interpreter is not only about calling functions and procedural programming, it also works with object-oriented PHP. This is how you can instantiate an object of class defined in a PHP:

my $instance = $PHP->instantiate('PHPclass', @args);

The instance is stored in $instance, and any arguments are passed to the class' constructor.

Example 2: Integrating Perl with PHP

The biggest advantage of Perl/PHP integration is PHP's ability to access Perl CPAN modules. There are CPAN modules for almost everything that can be done via software; you can use PHP::Interpreter in PHP to call CPAN modules to extend a PHP application to do anything, which is not native to PHP—for example, it enables you to write to IO ports. Writing to IO ports has been the exclusive domain of C/C++ programs, but with PHP::Interpreter, even a mere scripting language can have the capability to write to IO ports. The example that follows shows how to use Perl code with PHP, but first, we discuss the features of PHP::Interpreter that allow PHP/Perl integration.

The PHP interpreter, invoked via PHP::Interpreter, has a special class that allows PHP to Perl communication. Create an instance of the class via this call in PHP:

1. <?php
2. $perl = Perl::getInstance();
3. ?>

The new $perl object allows you to evaluate specific Perl instructions in PHP, such as:

1. <?php
2. $perl = Perl::getInstance();
3. $perl->eval(q^
4. print "Executing Perl code in PHP\n";
5. ^);
6. ?>

Similar to Example 1, where we called a PHP function in Perl, you can call Perl subroutines in PHP. All subroutines defined in the Perl program, which instantiated the PHP::Interpreter instance, can be invoked like this (I will provide a more detailed example shortly):

1. <?php
2. $perl = Perl::getInstance();
3. $return = $perl->call('sub', @args);
4. ?>

And, of course, you can get and set variables from the Perl file that instantiated the PHP::Interpreter; however, only package variables, not lexical variables, are supported.

Let's look at a practical application of PHP/Perl integration—for example, a snippet of Perl code that uses the Babel Fish CPAN module. (Babel Fish is a piece of software that allows you to translate text between different languages. To learn more about Babel Fish, go to The PHP program calls the translate function, which will be implemented in Perl, to translate a string in English to German and retrieve the output.

To install the Babel Fish CPAN, go to, and install it with the standard installation procedure, as shown previously in this article.

AltaVista::BabelFish also has some prerequisites, such as Class::Std and Class::Std::Util. These need to be downloaded and installed for Babel Fish to work:

1. use AltaVista::BabelFish;
2. use PHP::Interpreter;
3. my $p = PHP::Interpreter->new();
4. $p->include("phpscript.php");
5. my $val = $p->invoke();

6. sub translate
7. {
8. my $phish = AltaVista::BabelFish->new({ source => $_[0], target =>
   $_[1] });
9. return $phish->translate($_[2]) or die $phish->get_errstr();
10. }

The phpscript.php file contains the following:

1. <?php
2. function invoke()
3. {
4. $perl = Perl::getInstance();
5. $string = $perl->call('translate', 'en','de','Translate this for me');
6. print "Translated string: $string\n";|
7. }
8. ?>

Let's look at this piece of code in more detail. In line 4 of the PHP program, we are creating an instance of the Perl class using Perl::getInstance(). This is the special class inserted by the PHP::Interpreter dynamically into the environment to achieve PHP to Perl integration.

In line 5, we then use the class object, $perl, to invoke a function called translate, which is defined in line 6 of the Perl program, and we pass the arguments accordingly. The subroutine translate is invoked from the Perl script, and the translation is done via the Babel Fish module. The translated string is returned to PHP and printed via the print statement. Although this is a rudimentary example, the entire script can be extended to provide runtime translation for viewers of a dynamic Web page generated from PHP. With CPAN and the PHP::Interpreter, the possibilities of what can be achieved in PHP are bounded only by the developer's imagination.

You can use the PHP Perl class for object-oriented Perl as well. Invoke a Perl object via the new() function, as follows:

1. <?php
2. $perl = Perl::getInstance();
3. $instance = $perl->new('perlclass', @args);
4. ?>

The first argument to the new() method, in line 3, is the name of the class, and additional arguments are passed to the constructor of the class.



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Installation of PHP::Interpretor

Frederic_s_from_DE's picture

Hi there!

I'm using a xampp installation under Windows. Sadly, I'm restricted to using a Windows environment. Is there any way to install the PHP::Interpretor in this environment? When running the, I always get the error php-config not found. I don't quite understand what to do here. Maybe someone could help me? Thank you very much :-)

PHP and Perl Integration

Alagappan's picture

Good Article to know about Perl and PHP Integration. Thanks a lot.

there is no information or

Anonymous's picture

there is no information or not obvious information on how to get the perl in php module or how to install it.


Alexandr Ciornii's picture

It is not evident, but you should use DBD::Sybase to access MS SQL. Also you can use DBD::ODBC and several other modules.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState