Skip to content

Instantly share code, notes, and snippets.

@hamstar
Created May 7, 2011 15:04
Show Gist options
  • Save hamstar/960567 to your computer and use it in GitHub Desktop.
Save hamstar/960567 to your computer and use it in GitHub Desktop.
Nice wrapper for the exec command
<?php
class ShellCommand {
private $last_line;
private $cmd;
private $output = array();
private $return_value;
function __construct( $cmd, $escape=true ) {
if ( $escape ) {
$cmd = escapeshellcmd( $cmd );
}
$this->cmd = $cmd;
$this->last_line = exec( $cmd, $this->output, $this->return_value );
}
/**
* return string output in a newline separated string
*/
function __toString() {
return implode( "\n", $this->output );
}
/**
* return boolean true if command succeeded
*/
function __invoke() {
if ( $this->return_value == 0 ) {
return true;
}
return false;
}
/**
* return string the last line of output
*/
function getLastLine() {
return $this->last_line;
}
/**
* return array of output lines
*/
function getOutput() {
return $this->output;
}
/**
* return integer the return value
*/
function getReturnValue() {
return $this->return_value;
}
/**
* return string the command that was executed
*/
function getCommand() {
return $this->cmd;
}
}
<?php
include 'shellcommand.php';
$cmd = new ShellCommand('ls');
echo "Executed the command: {$cmd->getCommand()}\n";
if ( $cmd() ) {
echo $cmd;
} else {
echo "Failed with return value {$cmd->getReturnValue()}";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment