PHPackages                             tivie/command - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. tivie/command

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

tivie/command
=============

An utility library that harmonizes OS differences and executes external programs in a safer way

0.2.2(11y ago)1259.2k↑217.4%2[1 issues](https://github.com/tivie/command/issues)[1 PRs](https://github.com/tivie/command/pulls)1APACHE 2.0PHPPHP &gt;=5.3.0CI failing

Since Dec 16Pushed 2y ago1 watchersCompare

[ Source](https://github.com/tivie/command)[ Packagist](https://packagist.org/packages/tivie/command)[ Docs](http://tivie.github.com/command/)[ RSS](/packages/tivie-command/feed)WikiDiscussions master Synced 2d ago

READMEChangelogDependencies (2)Versions (6)Used By (1)

Command
=======

[](#command)

[![Build Status](https://camo.githubusercontent.com/a0945aac5ee04713ffe1191a608a5335f2da9334d65a403b961e9c06a071f7c3/68747470733a2f2f7472617669732d63692e6f72672f74697669652f636f6d6d616e642e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/tivie/command)[![Latest Stable Version](https://camo.githubusercontent.com/5574ca61e145a7bcdac4bf9505748e4fe456eab0292cf48f77c3e1429c38105c/68747470733a2f2f706f7365722e707567782e6f72672f74697669652f636f6d6d616e642f762f737461626c652e737667)](https://packagist.org/packages/tivie/command)[![License](https://camo.githubusercontent.com/5e98b1ec088bf59d05fe277ed069ed068196c072395a459223d5778496c48e01/68747470733a2f2f706f7365722e707567782e6f72672f74697669652f636f6d6d616e642f6c6963656e73652e737667)](https://packagist.org/packages/tivie/command)

A cross-platform PHP utility library that harmonizes OS differences and executes external programs in a safer way

Introduction
------------

[](#introduction)

Command is a small lightweight utility library that enables you to run external programs or commands in a safer way. It also harmonizes the differences between Windows and Unix environments, removing the need to create specific code for each platform.

Features
--------

[](#features)

- Platform independent: run the same code in Unix and Windows
- Fixes issues with `proc_open` in windows environment
- Object Oriented command builder with fluent interface
- Argument escaping, for safer command calls
- Command chaining with support for conditional calls and piping in both Windows and Unix environment

Installation
------------

[](#installation)

You can install it by cloning the git repository or using composer.

### Git clone

[](#git-clone)

```
git clone https://github.com/tivie/command.git

```

### Composer

[](#composer)

Add these lines to your composer.json:

```
    {
        "require": {
            "tivie/command": "*"
        }
    }
```

or run the following command:

```
php composer.phar require tivie/command

```

Quick Usage guide
-----------------

[](#quick-usage-guide)

### Simple example

[](#simple-example)

Let's say we want to 'ping' google.com 3 times with 32bytes packets. With PHP we could do something like this:

```
exec("ping -c 3 -s 24 www.google.com", $otp, $ec);
```

We want, however, to make our command a little bit safer and escape our arguments.

```
$host = 'www.google.com';
$c = 3;
$s = 24; //Linux adds 8 bytes of ICMP header data
$cmd = sprintf("ping -c %d -s %d %s", escapeshellarg($c), escapeshellarg($s), escapeshellarg($host));
exec($cmd, $otp, $ec);
```

This will work as expected in a GNU/Linux environment but will fail on Windows, since '-c' is an unrecognized flag and '-s' means something entirely different. The windows version would be :

```
$host = 'www.google.com';
$c = 3;
$s = 32;
$cmd = sprintf("ping -n %d -l %d %s", escapeshellarg($c), escapeshellarg($s), escapeshellarg($host));
exec($cmd, $otp, $ec);
```

If we want to ensure cross platform compatibility we will need to perform some kind of OS check and run the appropriate command based on that check:

```
$host = 'www.google.com';
$c = 3;
if (PHP_OS === 'WINDOWS' || PHP_OS === 'WIN32' || PHP_OS === 'WINNT' /* And a few more*/ ) {
    $s = 32;
    $cmd = sprintf("ping -n %d -l %d %s", escapeshellarg($c), escapeshellarg($s), escapeshellarg($host));
} else {
    $s = 24; //Linux adds 8 bytes of ICMP header data
    $cmd = sprintf("ping -c %d -s %d %s", escapeshellarg($c), escapeshellarg($s), escapeshellarg($host));
}
exec($cmd, $otp, $ec);
```

While this works in most cases, with more complex commands (or command chains) you would be forced to repeat yourself a lot, with a lot of conditional checks.

**With command library, you don't need to: it will do this work for you.**

```
$cmd = new \Tivie\Command\Command(\Tivie\Command\ESCAPE);
$cmd->setCommand('ping')
    ->addArgument(
        new Argument('-n', 3, \Tivie\OS\WINDOWS_FAMILY)
    )
    ->addArgument(
        new Argument('-l', 32, \Tivie\OS\WINDOWS_FAMILY)
    )
    ->addArgument(
        new Argument('-c', 3, \Tivie\OS\UNIX_FAMILY)
    )
    ->addArgument(
        new Argument('-s', 24, \Tivie\OS\UNIX_FAMILY)
    )
    ->addArgument(
        new Argument('www.google.com')
    );

$result = $cmd->run();
```

`Command::run()` returns a [Result object](https://github.com/tivie/command/blob/master/src/Result.php) that you can access to retrieve the result of the command.

```
echo $result->getStdOut();    // The Standard Output of the command
echo $result->getLastLine();  // The last line of the Standard Output
echo $result->getStdIn();     // The passed standard input
echo $result->getStdErr();    // The standard error
echo $result->getExitCode();  // The command's exit code
```

### Chaining commands

[](#chaining-commands)

Command library supports command chaining

```
$cmd1 = new \Tivie\Command\Command();
$cmd1->setCommand('php')
    ->addArgument(new Argument('-v'));

$cmd2 = new \Tivie\Command\Command();
$cmd2->setCommand('echo')
    ->addArgument(new Argument('foo'));

$results = $cmd1->chain()
                ->add($cmd2)
                /* any number of commands here */
                ->run();
```

`$results` will be an array of [Result objects](https://github.com/tivie/command/blob/master/src/Result.php).

You can also specify chaining conditions, similar to Linux's Chaining Operators.

#### RUN\_REGARDLESS (';')

[](#run_regardless-)

```
$cmd1->chain()->add($cmd2, \Tivie\Command\RUN_REGARDLESS)->run();
```

`$cmd2` will be run regardless of the exitcode of `$cmd1`. Mimics the ';' chaining operator and is the default action.

#### RUN\_IF\_PREVIOUS\_SUCCEEDS ('&amp;&amp;')

[](#run_if_previous_succeeds-)

```
$cmd1->chain()->add($cmd2, \Tivie\Command\RUN_IF_PREVIOUS_SUCCEEDS)->run();
```

`$cmd2` will only be run if `$cmd1` is successful, that is, if it exits with exitcode 0. Mimics the '&amp;&amp;' chaining operator.

#### RUN\_IF\_PREVIOUS\_FAILS ('||')

[](#run_if_previous_fails-)

```
$cmd1->chain()->add($cmd2, \Tivie\Command\RUN_IF_PREVIOUS_FAILS)->run();
```

`$cmd2` will only be run if `$cmd1` is not successful, that is, if it exits with exitcode different than 0. Mimics the '||' chaining operator.

#### Complex command chains

[](#complex-command-chains)

That being said, you can create complex command chains. For instance:

```
$cmd1->chain()
     ->add($cmd2, \Tivie\Command\RUN_IF_PREVIOUS_SUCCEEDS)
     ->add($cmd3, \Tivie\Command\RUN_IF_PREVIOUS_FAILS)
     ->add($cmd4, \Tivie\Command\RUN_REGARDLESS)
     ->run();
```

This will:

1. Run `$cmd1`
2. If `$cmd1` is successful then runs `$cmd2`
3. If `$cmd1` or `$cmd2` fails it will run `$cmd3`
4. Finally will run `$cmd4`

### Piping

[](#piping)

Command library supports 2 types of piping:

- **STDOUT-&gt;STDIN**
- **STDOUT-&gt;Argument**

#### STDOUT to STDIN

[](#stdout-to-stdin)

Piping the standard output of one command to the next's standard input is easy. You just need to set the third argument of [`Chain::add()`](https://github.com/tivie/command/blob/master/src/Chain.php) to `true`.

```
$cmd1->chain()->add($cmd2, \Tivie\Command\RUN_REGARDLESS, true)
```

#### STDOUT to Arguments

[](#stdout-to-arguments)

You can also pass the STDOUT of previous command as an argument of the next command. The library will look for the special keyword (placeholder) ***'!PIPE!'*** in the command's argument key and values and replace them with the previous command's STDOUT. You will then need to pass true as the third argument in [`Chain::add()`](https://github.com/tivie/command/blob/master/src/Chain.php) function, same as the above case.

```
$cmd2->addArgument(new Argument('foo'), \Tivie\Command\PIPE_PH); // PIPE_PH = '!PIPE!'
$cmd1->chain()->add($cmd2, \Tivie\Command\RUN_REGARDLESS, true);
```

Add support for other OS
------------------------

[](#add-support-for-other-os)

IF you need to more specific OS checks, you can extend [Detector class](https://github.com/tivie/php-os-detector/blob/master/src/Detector.php) or create a new class that implements [DetectorInterface](https://github.com/tivie/php-os-detector/blob/master/src/DetectorInterface.php). For further information, please read the [php-os-detector](https://github.com/tivie/php-os-detector) documentation.

Example:

```
const OS_2_WARP  = 65540; //65536 + 4

class MyOSDetector extends \Tivie\OS\Detector
{
    public function detect()
    {
        $os = parent::detect();

        switch($os->name) {
            case "OS/2":
            case "OS/2 WARP":
                $os->family = \Tivie\Command\OS\OTHER_FAMILY;
                $os->def = OS_2_WARP;
                break;
        }

        return $os;
    }
}
```

You don't need to create a new constant pertaining the new OS (you can use one of the pre existing families). If, however, you choose to do so, the new OS const value should be a unique number in the 2^n sequence plus the family the OS belongs to. In the example we chose 16th term (65536) plus the OS family (in this case, FAMILY\_OTHER) which is 4.

Contribute
----------

[](#contribute)

Feel free to contribute by forking or making suggestions.

Issue tracker:

Source code:

### Contributors

[](#contributors)

[Tivie](http://tivie.github.com/Tivie)[Sophie-OS](https://github.com/Sophie-OS)

License
-------

[](#license)

Command Library is released under Apache 2.0 license. For more information, please consult the [LICENSE](https://github.com/tivie/commandr/blob/master/LICENSE) file in this repository or .

###  Health Score

33

—

LowBetter than 72% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity37

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 94.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~3 days

Total

4

Last Release

4210d ago

PHP version history (2 changes)0.1.0PHP &gt;=5.4.0

0.2.1PHP &gt;=5.3.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/1f735d8fb97242e69e2da4cd77f5a98114b307e042d91c9316803243744d9f7e?d=identicon)[Tivie](/maintainers/Tivie)

---

Top Contributors

[![tivie](https://avatars.githubusercontent.com/u/1608730?v=4)](https://github.com/tivie "tivie (35 commits)")[![Sophie-OS](https://avatars.githubusercontent.com/u/10285178?v=4)](https://github.com/Sophie-OS "Sophie-OS (2 commits)")

---

Tags

execproc\_openexternal programs

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/tivie-command/health.svg)

```
[![Health](https://phpackages.com/badges/tivie-command/health.svg)](https://phpackages.com/packages/tivie-command)
```

###  Alternatives

[pastuhov/php-exec-command

Simple php command executor with param binding.

25206.1k2](/packages/pastuhov-php-exec-command)[wyrihaximus/file-descriptors

List open file descriptors for the current process cross platform

16266.3k2](/packages/wyrihaximus-file-descriptors)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
