PHP passing variables to Perl, having issues with using spaces between variables method, is there another, better way?
I find myself needing to use Perl more and more since PHP's regular expressions leave me wondering what is going on half the time as they simply don't respond as they should (as they do when I use Perl, for e开发者_如何学编程xample)... i had been using this method to call perl (before i started trying to do this with regular expressions).. passing in a regex string as a variable causes all sorts of problems, such as using " ( )" anywhere makes it not work, among other things.. I am wondering if there is a better way to do this, than the string of variables after the perl filename method as it seems to have some glaring limiations.. thanks for any info.
the way I do it currently:
$file = "/pathtomy/perlscript.pl $var1 $var2 $var3" ;
ob_start();
passthru($file);
$perlreturn = ob_get_contents();
ob_end_clean();
return $perlreturn;
For the general case, you'll want to use escapeshellarg
. Blindly wrapping everything in single quotes works most of the time but will fail when one of your arguments contains a single quote!
string escapeshellarg ( string $arg )
escapeshellarg()
adds single quotes around a string and quotes/escapes any existing single quotes allowing you to pass a string directly to a shell function and having it be treated as a single safe argument. This function should be used to escape individual arguments to shell functions coming from user input. The shell functions includeexec()
,system()
and the backtick operator.
Using a simple Perl program that prints its command-line arguments
#! /usr/bin/perl
$" = "]["; # " fix StackOverflow highlighting
print "[@ARGV]\n";
and then a modified version of the PHP program from your question
<?php
$var1 = "I'm a";
$var2 = "good boy,";
$var3 = "I am.";
$file = "./prog.pl " . implode(" ",
array_map("escapeshellarg",
array($var1,$var2,$var3)));
echo "command=", $file, "\n";
ob_start();
passthru($file);
$perlreturn = ob_get_contents();
ob_end_clean();
echo "return=", $perlreturn;
?>
we see the following output:
$ php prog.php command=./prog.pl 'I'\''m a' 'good boy,' 'I am.' return=[I'm a][good boy,][I am.]
Try to use quotation marks:
$file = "/pathtomy/perlscript.pl '$var1' '$var2' '$var3'" ;
精彩评论