2011-09-07 43 views
3

我有一个包含一个长字符串的变量。 (特别是它包含几千字节的JavaScript代码)如何在php中通过外部命令传递变量的内容?

我想通过这个字符串通过一个外部命令,在这种情况下JavaScript压缩器,并捕获外部命令的输出(压缩的JavaScript)在PHP中,将其分配给一个变量。

我知道有类压缩在PHP中的JavaScript,但这只是一个普遍问题的例子。

最初我们使用:

$newvar = passthru("echo $oldvar | compressor"); 

这适用于小弦,但不安全。 (如果oldvar包含对shell有特殊含义的字符,则任何事情都可能发生)

使用escapeshellarg进行转义由于操作系统对最大允许参数长度的限制,修复了该问题,但解决方案因为较长的字符串而中断。

我尝试使用popen("command" "w")并写入命令 - 这是有效的,但命令的输出静静地消失在void中。

概念,我只想做等价的:

$newvar = external_command($oldvar); 

回答

2

使用proc_open -function你可以得到的句柄进程的标准输出和标准输入,从而将数据写入并读取结果。

0

使用rumpels的建议,我能够设备下面的解决方案,似乎运作良好。在此发布此信息可以让任何对此问题感兴趣的人感兴趣。

public static function extFilter($command, $content){ 
    $fds = 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("pipe", "w") // stderr is a pipe that the child will write to 
    ); 
    $process = proc_open($command, $fds, $pipes, NULL, NULL); 
    if (is_resource($process)) { 
     fwrite($pipes[0], $content); 
     fclose($pipes[0]); 
     $stdout = stream_get_contents($pipes[1]); 
     fclose($pipes[1]); 
     $stderr = stream_get_contents($pipes[2]); 
     fclose($pipes[2]); 
     $return_value = proc_close($process); 
     // Do whatever you want to do with $stderr and the commands exit-code. 
    } else { 
     // Do whatever you want to do if the command fails to start 
    } 
    return $stdout; 
} 

可能有死锁的问题:如果你发送的数据比管合尺寸越大,则外部命令将阻塞,等待有人来读取它的标准输出,而PHP被阻断,等待标准输入读取以为更多输入腾出空间。

可能PHP会以某种方式处理这个问题,但如果您打算发送(或接收)比适合管道更多的数据,则值得测试。