Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
POpen
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
8.01
0.00% covered (danger)
0.00%
0 / 1
 exec
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
8.01
1<?php
2
3namespace ExecWithFallback;
4
5/**
6 * Emulate exec() with system()
7 *
8 * @package    ExecWithFallback
9 * @author     Bjørn Rosell <it@rosell.dk>
10 */
11class POpen
12{
13
14  /**
15   * Emulate exec() with system()
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
26        $handle = @popen($command, "r");
27        if ($handle === false) {
28            return false;
29        }
30
31        $result = '';
32        while (!@feof($handle)) {
33            $result .= fread($handle, 1024);
34        }
35
36        //Note: Unix Only:
37        // pclose() is internally implemented using the waitpid(3) system call.
38        // To obtain the real exit status code the pcntl_wexitstatus() function should be used.
39        $result_code = pclose($handle);
40
41        $theOutput = preg_split('/\s*\r\n|\s*\n\r|\s*\n|\s*\r/', $result);
42
43        // remove the last element if it is blank
44        if ((count($theOutput) > 0) && ($theOutput[count($theOutput) -1] == '')) {
45            array_pop($theOutput);
46        }
47
48        if (count($theOutput) == 0) {
49            return '';
50        }
51        if (gettype($output) == 'array') {
52            foreach ($theOutput as $line) {
53                $output[] = $line;
54            }
55        } else {
56            $output = $theOutput;
57        }
58        return $theOutput[count($theOutput) -1];
59    }
60}