Php with perl scripts

Integrating PHP and Perl

Perl is a language often associated with text processing and CGI. PHP is a language often associated with dynamic Web pages. Both are very popular with Web developers. Often, each of these languages is used at the expense of the other. Hard-core Perl developers would love to develop everything in Perl, and PHP developers tend to stick with PHP.

As usual in the Open Source world, there is a lot of zealotry between users of each language. If you think that one of these languages is perfect and the other is lame, this article is not for you! This article is for those who take a more pragmatic approach and use what works best for them. Each language has its strengths and limitations. Personally, I use both languages at work and at home. With time, I have discovered which language is best for which tasks and try to integrate the strengths of each language as much as possible to complete my work quickly.

Perl is extremely good at system administration and extensive data processing, among other things. This means, if you want to do some extensive processing on a text report, Perl would be preferable, as it provides handy regular-expression-enabled text comparisons, which make it so much easier to search through a report. Perl also has extensive string manipulation features. Perl, by virtue of being older than PHP and having an extensive community, has thousands of extensions archived in CPAN, which allow one to do virtually anything with the language, conveniently. From XML processing to writing to parallel port devices, CPAN includes everything. CPAN is the reason Perl continues to be useful to a large number of developers to date. Although it is not impossible to do everything described here with PHP and a mixture of other languages, it’s simply more convenient with Perl.

Читайте также:  Eslint typescript react example

PHP is extremely good at integration with Web pages and databases. PHP integrates nicely with static HTML Web pages. That’s why it’s so popular and has had more visibility than Perl in recent years. It has mature support for numerous popular free or non-free databases and supports MS SQL (MSSQL) server better than any other open-source language. From personal experience, I have tried at least two CPAN extensions for Perl to get it to work with an MSSQL installation, but with limited success. However, PHP has seamless support for MSSQL and uses it as natively as MySQL.

I was recently involved in a project in which nearly the entire project was in Perl. However, a tiny bit of code needed access to an MSSQL server. I knew how simple it was in PHP to work with MSSQL, and I did not want to go through the pain of setting up my Perl installation for MSSQL. That’s why I searched the Internet for a way to integrate both languages in a manner that would allow me to use the best parts of each language and produce a coherent solution. And, I found the PHP::Interpreter CPAN module. PHP::Interpreter was perfect. It enables the complete integration of the two languages to an extent that one starts to believe that both are mere extensions of each other. PHP::Interpreter, as this article shows, allows you to use PHP’s mature support for databases and other features natively in Perl, and also to use Perl’s vast number of CPAN modules to extend your PHP programs.

According to AnnoCPAN, the module’s main function is to encapsulate an embedded PHP5 interpreter. It provides proxy methods (via AUTOLOAD) to all the functions declared in the PHP interpreter, transparent conversion of Perl data types to PHP (and vice versa), and the ability for PHP to call Perl subroutines similarly and access the Perl symbol table. The goal of this package is to construct a transparent bridge for running PHP code and Perl code side by side.

Читайте также:  Python finding key in dictionary

To demonstrate the power of this module, we code two examples to show each side of the PHP::Interpreter, integrating Perl with PHP and integrating PHP with Perl. Each example shows areas in which both languages complement each other nicely to produce powerful code.

In the first example, we create an application to monitor failed logins through SSH to our system. SSH often is targeted by script kiddies and malicious users to compromise a system and gain access to it. The script identifies the IPs of the offenders, blocks all incoming packets from using iptables and, finally, logs them in to an MS SQL server database. We use Perl to do what it’s best at—processing log files. It will continuously monitor the /var/log/messages file, which the SSH dæmon uses to log failed login attempts. To monitor a log file continuously, we use the CPAN extension File::Tail. To support writing to MS SQL Server transparently, we implement this portion in PHP and show how the two languages can be integrated seamlessly and used in scenarios where both complement each other.

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:

Источник

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:

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.

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:

str ing 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 «

Источник

Вызов Perl-скрипта из PHP и передача в переменных, а также использование имени переменной perl-скрипта

Обычно я вызываю скрипты perl из PHP, как показано ниже, и передаю переменные таким образом, и он отлично работает, однако теперь я создаю компонент для повторного использования, где я хочу также изменить имя скрипта perl, которое я передаю, и это давая мне некоторые головные боли, поэтому мне интересно, может ли кто-нибудь указать лучший способ сделать это, поскольку мой способ не работает .. спасибо ..

способ, который работает без измененного имени файла perl:

$file = "/var/www/other_scripts/perl/apps/perlscript.pl $var1 $var2 $var3 $var4"; ob_start(); passthru($file); $perlreturn = ob_get_contents(); ob_end_clean(); 

Моя попытка изменить имя файла perl, который, похоже, не работает для меня, вы можете видеть в приведенном выше примере, как он включает даже $ var (s) в начальном «», который я нахожу нечетным, но это кажется единственный способ, которым он работает, и я не был уверен, как даже воспроизвести это с помощью переменной буквы perl:

$perlscript_file = "/var/www/other_scripts/perl/apps/" . $perlscript .".pl"; $file = $perlscript_file . $var1 . $var2 .$var3 . $var4; ob_start(); passthru($file); $perlreturn = ob_get_contents(); ob_end_clean(); 

Ваш способ не работает, потому что вы объединяете все параметры без пробелов, что делает их одним параметром.

$perlscript_file = "/var/www/other_scripts/perl/apps/$perlscript.pl $var1 $var2 $var3 $var4"; 

Кстати, если параметры поступают из внешнего источника, вы ДОЛЖНЫ их дезинфицировать с помощью escapeshellarg() . То же самое касается $perlscript – если он исходит из внешнего источника или даже ввода пользователя, выполните на нем escapeshellcmd() .

В обозревателе есть пакет CPAN, целью которого является создание моста между PHP и Perl, что позволит вам сделать что-то вроде следующего в PHP:

$perl = Perl::getInstance(); $instance = $perl->new('perlclass', @args); 

Не уверен, насколько это стабильно. Видеть

Если вы используете Apache, вы также можете использовать

// PHP apache_note('foo', 'bar'); virtual("/perl/some_script.pl"); $result = apache_note("resultdata"); # Perl my $r = Apache->request()->main(); my $foo = $r->notes('foo'); $r->notes('resultdata', somethingWithFoo($foo)); 

Во втором коде вы объединяете переменные без пробелов между ними. Вы должны рассмотреть возможность использования sprintf для его форматирования:

$script = sprintf('/var/www/other_scripts/perl/apps/%s.pl %s %s %s %s', $perlscript, $var1, $var2, $var3, $var4); 

Источник

Оцените статью