Integrating PHP and Perl
Setting up PHP::Interpreter is basically a standard Perl module installation procedure. You can get it from search.cpan.org/dist/PHP-Interpreter. Unpack it, and create the Makefile:
perl Makefile.PL
Compile it:
make
And, install it:
make install
You can do an additional:
pod2html interpreter.pm > 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 search.cpan.org/dist/File-Tail.
Unpack it, and create the Makefile:
perl MakeFile.PL make 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'
=>'threads_only');
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.
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 babel.altavista.com.) 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 search.cpan.org/CPAN/authors/id/D/DM/DMUEY/AltaVista-BabelFish-v42.0.1.tar.gz, 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.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- RSS Feeds
- Trying to Tame the Tablet
- New Products
- What's the tweeting protocol?
- Dart: a New Web Programming Experience
- Reply to comment | Linux Journal
1 hour 30 min ago - Drupal is an Awesome CMS and a Crappy development framework
6 hours 9 min ago - IT industry leaders
8 hours 32 min ago - Reply to comment | Linux Journal
1 day 1 hour ago - Reply to comment | Linux Journal
1 day 3 hours ago - Reply to comment | Linux Journal
1 day 5 hours ago - great post
1 day 5 hours ago - Google Docs
1 day 6 hours ago - Reply to comment | Linux Journal
1 day 10 hours ago - Reply to comment | Linux Journal
1 day 11 hours ago
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.




Comments
Installation of PHP::Interpretor
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 Makefile.pl, 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
Good Article to know about Perl and PHP Integration. Thanks a lot.
there is no information or
there is no information or not obvious information on how to get the perl in php module or how to install it.
MS SQL
It is not evident, but you should use DBD::Sybase to access MS SQL. Also you can use DBD::ODBC and several other modules.