Skip to content

Instantly share code, notes, and snippets.

@jtpaasch
Created July 25, 2013 15:57
Show Gist options
  • Save jtpaasch/6081158 to your computer and use it in GitHub Desktop.
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.
<?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