2016-01-20 17 views
7

JavaおよびPythonでは、エスケープされていない文字列を使用して簡単にプロセスを開始できるように、ProcessBuilderまたはsubprocessのモジュールがあります。 ["ls", "some unescaped directory name"] - stdout、stderrからの読み込みのような強力なツールも提供します。 exec()よりインテリジェントで便利なPHPの同等の機能はありますか?PHPのサブプロセスに相当するものはありますか?

+1

正直なところ、PHPはプロセスを実行しません。 –

+0

本当ですか?それは私が考えていたものですが、現代のPHP *ではPHPをBashのようなスクリプト言語として使用できると言います - "PHPは強力なコマンドラインアプリケーション(bash、Ruby、Pythonなど)を構築するためにも使用できます。多くのPHP開発者はこれを認識せず、本当にエキサイティングな機能を見逃しています。 - http://shop.oreilly.com/product/0636920033868.do – NoBugs

+0

[popen](http://php.net/manual/en/function.popen.php)が役立つかどうか不明です。 – Jigar

答えて

4

双方向通信でstdin,stdoutstderrにアクセスできる最も近いものはproc_open()です。ここで

は、ドキュメントからの例です:

<?php 
$descriptorspec = array(
    0 => array("pipe", "r"), // stdin is a pipe that the child will read from 
    1 => array("pipe", "w"), // stdout is a pipe that the child will write to 
    2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to 
); 

$cwd = '/tmp'; 
$env = array('some_option' => 'aeiou'); 

$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env); 

if (is_resource($process)) { 
    // $pipes now looks like this: 
    // 0 => writeable handle connected to child stdin 
    // 1 => readable handle connected to child stdout 
    // Any error output will be appended to /tmp/error-output.txt 

    fwrite($pipes[0], '<?php print_r($_ENV); ?>'); 
    fclose($pipes[0]); 

    echo stream_get_contents($pipes[1]); 
    fclose($pipes[1]); 

    // It is important that you close any pipes before calling 
    // proc_close in order to avoid a deadlock 
    $return_value = proc_close($process); 

    echo "command returned $return_value\n"; 
} 
?> 

あなただけstdoutstdinが必要な場合は、popen()を使用することができます。

マニュアルの吸うので、これは、私の変形例である:

<?php 
$handle = popen('/path/to/executable', 'r'); 

$lines = []; 
while (!feof($handle)) 
{ 
    $lines[] = fgets($handle); 
} 

pclose($handle); 

これは、出力のラインの配列に/path/to/executableの出力を読み込みます。

また、エスケープする引数についても尋ねました。あなたはescapeshellarg()でそれを行うことができます:

$escapedArg = escapeshellarg($arg); 
関連する問題