Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
95.65% |
22 / 23 |
|
0.00% |
0 / 1 |
CRAP | |
0.00% |
0 / 1 |
| ProcOpen | |
95.65% |
22 / 23 |
|
0.00% |
0 / 1 |
7 | |
0.00% |
0 / 1 |
| exec | |
95.65% |
22 / 23 |
|
0.00% |
0 / 1 |
7 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace ExecWithFallback; |
| 4 | |
| 5 | /** |
| 6 | * Emulate exec() with proc_open() |
| 7 | * |
| 8 | * @package ExecWithFallback |
| 9 | * @author Bjørn Rosell <it@rosell.dk> |
| 10 | */ |
| 11 | class ProcOpen |
| 12 | { |
| 13 | |
| 14 | /** |
| 15 | * Emulate exec() with proc_open() |
| 16 | * |
| 17 | * @param string $command The command to execute |
| 18 | * @param string &$output (optional) |
| 19 | * @param int &$result_code (optional) |
| 20 | * |
| 21 | * @return string | false The last line of output or false in case of failure |
| 22 | */ |
| 23 | public static function exec($command, &$output = null, &$result_code = null) |
| 24 | { |
| 25 | $descriptorspec = array( |
| 26 | //0 => array("pipe", "r"), |
| 27 | 1 => array("pipe", "w"), |
| 28 | //2 => array("pipe", "w"), |
| 29 | //2 => array("file", "/tmp/error-output.txt", "a") |
| 30 | ); |
| 31 | |
| 32 | $cwd = getcwd(); // or is "/tmp" better? |
| 33 | $processHandle = proc_open($command, $descriptorspec, $pipes, $cwd); |
| 34 | $result = ""; |
| 35 | if (is_resource($processHandle)) { |
| 36 | // Got this solution here: |
| 37 | // https://stackoverflow.com/questions/5673740/php-or-apache-exec-popen-system-and-proc-open-commands-do-not-execute-any-com |
| 38 | //fclose($pipes[0]); |
| 39 | $result = stream_get_contents($pipes[1]); |
| 40 | fclose($pipes[1]); |
| 41 | //fclose($pipes[2]); |
| 42 | $result_code = proc_close($processHandle); |
| 43 | |
| 44 | // split new lines. Also remove trailing space, as exec() does |
| 45 | $theOutput = preg_split('/\s*\r\n|\s*\n\r|\s*\n|\s*\r/', $result); |
| 46 | |
| 47 | // remove the last element if it is blank |
| 48 | if ((count($theOutput) > 0) && ($theOutput[count($theOutput) -1] == '')) { |
| 49 | array_pop($theOutput); |
| 50 | } |
| 51 | |
| 52 | if (count($theOutput) == 0) { |
| 53 | return ''; |
| 54 | } |
| 55 | if (gettype($output) == 'array') { |
| 56 | foreach ($theOutput as $line) { |
| 57 | $output[] = $line; |
| 58 | } |
| 59 | } else { |
| 60 | $output = $theOutput; |
| 61 | } |
| 62 | return $theOutput[count($theOutput) -1]; |
| 63 | } else { |
| 64 | return false; |
| 65 | } |
| 66 | } |
| 67 | } |