Skip to content

Instantly share code, notes, and snippets.

@hugochinchilla
Forked from vglebov/Exec.php
Last active December 23, 2015 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugochinchilla/6610706 to your computer and use it in GitHub Desktop.
Save hugochinchilla/6610706 to your computer and use it in GitHub Desktop.
<?php
$e = Exec::withCommandLine($cmd)->launch();
if ($e->getResultCode() !== 0) {
$message = join("\n", $e->getOutput());
throw new Exception($message);
}
<?php
class Exec {
protected $commandLine;
protected $resultCode = 0;
protected $stdout;
protected $stderr;
public static function withCommandLine($commandLine){
return new self($commandLine);
}
function __construct($commandLine)
{
$this->commandLine = $commandLine;
}
public function launch()
{
$descriptorspec = array(
["file", "php://stdin", "r"], // stdin
["pipe", "w"], // stdout
["pipe", "w"], // stderr
);
$proc = proc_open($this->commandLine, $descriptorspec, $pipes);
$this->stdout = array_filter(explode("\n", stream_get_contents($pipes[1])));
$this->stderr = array_filter(explode("\n", stream_get_contents($pipes[2])));
fclose($pipes[1]);
fclose($pipes[2]);
$this->resultCode = proc_close($proc);
return $this;
}
public function getCommandLine()
{
return $this->commandLine;
}
public function getResultCode()
{
return $this->resultCode;
}
public function getStdErr()
{
return $this->stderr;
}
public function getStdOut()
{
return $this->stdout;
}
public static function sanitize($input)
{
return escapeshellcmd($input);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment