Home

Awesome

php-shellcommand

GitHub Tests Packagist Version Packagist Downloads GitHub license Packagist PHP Version Support

php-shellcommand provides a simple object oriented interface to execute shell commands.

Installing

Prerequisites

Your php version must be 5.4 or later.

Installing with composer

This package can be installed easily using composer.

composer require mikehaertl/php-shellcommand

Features

Examples

Basic Example

<?php
use mikehaertl\shellcommand\Command;

// Basic example
$command = new Command('/usr/local/bin/mycommand -a -b');
if ($command->execute()) {
    echo $command->getOutput();
} else {
    echo $command->getError();
    $exitCode = $command->getExitCode();
}

Advanced Features

Add Arguments

<?php
$command = new Command('/bin/somecommand');
// Add arguments with correct escaping:
// results in --name='d'\''Artagnan'
$command->addArg('--name=', "d'Artagnan");

// Add argument with several values
// results in --keys key1 key2
$command->addArg('--keys', ['key1','key2']);

Pipe Input Into Command

From string:

<?php
$command = new ('jq'); // jq is a pretty printer
$command->setStdIn('{"foo": 0}');
if (!$command->execute()) {
    echo $command->getError();
} else {
    echo $command->getOutput();
}
// Output:
// {
//   "foo": 0
// }

From file:

<?php
$fh = fopen('test.json', 'r');
// error checks left out...
$command = new Command('jq');
$command->setStdIn($fh);
if (!$command->execute()) {
    echo $command->getError();
} else {
    echo $command->getOutput();
}
fclose($fh);

From URL:

<?php
$fh = fopen('https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m,relativehumidity_2m,windspeed_10m', 'r');
// error checks left out...
$command = new Command('jq');
$command->setStdIn($fh);
if (!$command->execute()) {
    echo $command->getError();
} else {
    echo $command->getOutput();
}
fclose($fh);

Set Command Instance Options

<?php
// Create command with options array
$command = new Command([
    'command' => '/usr/local/bin/mycommand',

    // Will be passed as environment variables to the command
    'procEnv' => [
        'DEMOVAR' => 'demovalue'
    ],

    // Will be passed as options to proc_open()
    'procOptions' => [
        'bypass_shell' => true,
    ],
]);

API

Properties

You can configure all these properties via an array that you pass in the constructor. You can also pass command, execCommand and args as options. This will call the respective setter (setCommand(), setExecCommand(), etc.).

Methods

Note: getError(), getStdErr() and getOutput() return the trimmed output. You can pass false to these methods if you need any possible line breaks at the end.