Created
July 25, 2013 15:57
-
-
Save jtpaasch/6081158 to your computer and use it in GitHub Desktop.
A simple OS class that helps PHP run commands on the command line.
This file contains 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 | |
/** | |
* The `OS` class helps run | |
* commands on the command line. | |
* | |
* @author JT Paasch | |
*/ | |
class OS { | |
/** | |
* Run a command on the command line. | |
* | |
* @access public | |
* @param String $command The command to run (include param/options). | |
* @param String $input The input to give to the command (if any). | |
* @return Array The results with 'output', 'error', and 'code'. | |
*/ | |
public static function run($command, $input=null) { | |
// Let's identify the streams/pipes we want to use. | |
// We want STDIN (0), STDOUT (1), and STDERR (2). | |
$interface = array( | |
0 => array('pipe', 'r'), // STDIN reads what we give it. | |
1 => array('pipe', 'w'), // STDOUT writes to the stream. | |
2 => array('pipe', 'w'), // STDERR writes to the stream. | |
); | |
// Open the process. After this, We'll be able to access | |
// the pipes/streams through the $pipe array. | |
// That is, $pipe[0] will access $interface[0], | |
// $pipe[1] will access $interface[1], and so on. | |
$process = proc_open($command, $interface, $pipe); | |
// If we need to give the command some input, do so now: | |
if (!empty($input)) { | |
fwrite($pipe[0], $input); | |
} | |
// Close the input stream, so the command knows it can go ahead. | |
fclose($pipe[0]); | |
// Read the STDOUT and STDERR pipes. | |
$output = @stream_get_contents($pipe[1]); | |
$error = @stream_get_contents($pipe[2]); | |
// Close the STDOUT and STDERR pipes. | |
fclose($pipe[1]); | |
fclose($pipe[2]); | |
// Close the process. | |
$exit_code = proc_close($process); | |
// Return the results. | |
return array( | |
'output' => $output, | |
'error' => $error, | |
'code' => $exit_code, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment