2011-09-07 25 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會以某種方式處理這個問題,但如果您打算髮送(或接收)比適合管道更多的數據,則值得測試。