| 1 |
<?php |
| 2 |
|
| 3 |
namespace ExecWithFallback; |
| 4 |
|
| 5 |
/** |
| 6 |
* Emulate exec() with system() |
| 7 |
* |
| 8 |
* @package ExecWithFallback |
| 9 |
* @author Bjørn Rosell <[email protected]> |
| 10 |
*/ |
| 11 |
class ShellExec |
| 12 |
{ |
| 13 |
|
| 14 |
/** |
| 15 |
* Emulate exec() with shell_exec() |
| 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 |
$resultCodeSupplied = (func_num_args() >= 3); |
| 26 |
if ($resultCodeSupplied) { |
| 27 |
throw new \Exception('ShellExec::exec() does not support $result_code argument'); |
| 28 |
} |
| 29 |
|
| 30 |
$result = shell_exec($command); |
| 31 |
|
| 32 |
// result: |
| 33 |
// - A string containing the output from the executed command, |
| 34 |
// - false if the pipe cannot be established |
| 35 |
// - or null if an error occurs or the command produces no output. |
| 36 |
|
| 37 |
if ($result === false) { |
| 38 |
return false; |
| 39 |
} |
| 40 |
if (is_null($result)) { |
| 41 |
// hm, "null if an error occurs or the command produces no output." |
| 42 |
// What were they thinking? |
| 43 |
// And yes, it does return null, when no output, which is confirmed in the test "echo hi 1>/dev/null" |
| 44 |
// What should we do? Throw or accept? |
| 45 |
// Perhaps shell_exec throws in newer versions of PHP instead of returning null. |
| 46 |
// We are counting on it until proved wrong. |
| 47 |
return ''; |
| 48 |
} |
| 49 |
|
| 50 |
$theOutput = preg_split('/\s*\r\n|\s*\n\r|\s*\n|\s*\r/', $result); |
| 51 |
|
| 52 |
// remove the last element if it is blank |
| 53 |
if ((count($theOutput) > 0) && ($theOutput[count($theOutput) -1] == '')) { |
| 54 |
array_pop($theOutput); |
| 55 |
} |
| 56 |
|
| 57 |
if (count($theOutput) == 0) { |
| 58 |
return ''; |
| 59 |
} |
| 60 |
if (gettype($output) == 'array') { |
| 61 |
foreach ($theOutput as $line) { |
| 62 |
$output[] = $line; |
| 63 |
} |
| 64 |
} else { |
| 65 |
$output = $theOutput; |
| 66 |
} |
| 67 |
return $theOutput[count($theOutput) -1]; |
| 68 |
} |
| 69 |
} |
| 70 |
|