[ Perl tips index ]
[ Subscribe to Perl tips ]

Perl is a great language to extend and integrate existing applications, even if they're written in other languages. The Inline:: modules allow many languages to be embedded directly into Perl's source code, including C, Java, Python, and Ruby. However many other languages are not yet supported by the Inline:: framework, and PHP is one of these.

It's always been possible to call PHP from Perl and vice-versa by using the system function, but this sort of coarse-grained integration is rarely what most developers desire. However recently the support for integrating PHP and Perl has become significantly better.

George Schlossnagle's PHP::Interpreter module allows a developer to create a PHP interpreter that runs inside of Perl. This can then be used to call PHP functions, execute PHP files, and create and manipulate PHP objects from Perl. It even allows the reverse, writing PHP code that makes use of Perl's powerful features and modules.

Using PHP from Perl

        use strict;
        use warnings;

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

        # Include a PHP file

        # Call a PHP function (for example checkdate)
        my $is_valid = $p->checkdate($month, $day, $year);

Using Perl from PHP

First you need to create a wrapper script, to be called instead of the usual PHP interpretor.

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

After that, you can write your PHP code as usual:

        # script_to_execute.php

        # Access our Perl interpreter.
        $perl = Perl::getInstance();

        # Use the DBI module.

        $perl->eval("use DBI");

        # Now create a DBI object.  Even though this is a Perl object,
        # we can treat it like it's a native PHP object.

        $dbh = $perl->eval( "DBI->connect($dsn, $user, $pass)" );
        $dbh->do("DELETE FROM customers WHERE domain = '' ");


Other PHP interfaces

There's more than one way to communicate with PHP from Perl. Dmitry Karasik's PHP module provides similar features to PHP::Interpreter, and Tatsuhiko Miyagawa's PHP::Session allows manipulation of PHP sessions, allowing common sessions between Perl and PHP applications.

[ Perl tips index ]
[ Subscribe to Perl tips ]

This Perl tip and associated text is copyright Perl Training Australia. You may freely distribute this text so long as it is distributed in full with this Copyright noticed attached.

If you have any questions please don't hesitate to contact us:

Phone: 03 9354 6001 (Australia)
International: +61 3 9354 6001

Valid XHTML 1.0 Valid CSS