Created
June 14, 2018 15:37
-
-
Save Luxian/d626593bbc1f22a4126065edf13966d0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| include __DIR__ . '/Shell.php'; | |
| // List entries | |
| $command = Shell::exec("ls -l"); | |
| if ($command->failed()) { | |
| echo "Failed to list entries!\n"; | |
| exit(__LINE__); // exit script with error code (non-zero), using line number might make debuggin easier | |
| } | |
| else { | |
| echo "Entries: \n" . $command->output; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class Shell { | |
| public $command; | |
| public $output_array; | |
| public $output; | |
| public $exit_code; | |
| public function __construct($command, $exit_code, array $output_array) { | |
| $this->command = $command; | |
| $this->exit_code = $exit_code; | |
| $this->output = implode("\n", $output_array); | |
| $this->output_array = $output_array; | |
| } | |
| /** | |
| * Run command and capture output and exit code | |
| * | |
| * @param string $command | |
| * Shell command to execute | |
| * @param bool $capture_errors | |
| * Set this to TRUE to include errors in output string | |
| * | |
| * @return static | |
| */ | |
| public static function exec($command, $capture_errors = TRUE) { | |
| ob_start(); | |
| $output_array = array(); | |
| exec($command . ($capture_errors ? ' 2>&1' : ''), $output_array, $exit_code); | |
| ob_end_clean(); | |
| return new static($command, $exit_code, $output_array); | |
| } | |
| /** | |
| * Returns TRUE if command failed with a non-zero exit code | |
| * | |
| * @return bool | |
| */ | |
| public function failed() { | |
| return $this->exit_code != 0; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment