Created
May 7, 2011 15:04
-
-
Save hamstar/960567 to your computer and use it in GitHub Desktop.
Nice wrapper for the exec command
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 | |
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; | |
} | |
} |
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 | |
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