php-standard-library/shell
Execute shell commands safely in PHP with built-in argument escaping and controlled handling of stdout/stderr. Part of PHP Standard Library, providing a simple API for running processes, capturing error output, and managing failures predictably.
exec() wrappers, cutting ~30% maintenance overhead for shell-related code.exec() calls), with semver compliance (6.x is backward-compatible).php artisan make:command). Add:
## Shell Commands
Use the `SystemCommand` service for safe shell execution:
```php
$this->systemCommand->run('git pull')->throwIfFailed();
CommandResult objects provide exit codes, stdout/stderr, and timing, simplifying support for:
docker build errors).npm install failures).throwIfFailed() integrates with Laravel’s exception handling:
try {
$result = $shell->run('dangerous-command')->throwIfFailed();
} catch (CommandFailedException $e) {
report($e); // Laravel’s error reporting
}
$shell->run('tail -f logfile.log')->stream(fn($chunk) =>
Log::channel('stream')->info($chunk)
);
SystemCommand::dispatch('git pull')->onQueue('shell-tasks');
php artisan shell:benchmark "docker build ."
| Failure Type | Impact | Mitigation |
|---|---|---|
| Command Injection | Security breach (e.g., rm -rf /) |
Use Shell::safe() or validate arguments. |
| Streaming Buffer Overflow | OOM crashes in long streams | Limit chunk size (e.g., 4KB) or use disk storage. |
| Cross-Platform Quirks | Windows cmd.exe buffering |
Test with php artisan shell:test --env=windows. |
| Async Job Failures | Lost streaming output | Store chunks in DB/Redis with retries. |
| Dependency Abandonment | Broken updates | Fork or migrate to Symfony Process if needed. |
Shell (never exec()).throwIfFailed() and Laravel’s report().## Shell Command Best Practices
- **Never**: `exec('user_input')` → **Always**: `$shell->safe('command', [$user_input])`.
- **For async**: Use `SystemCommand::dispatch()` with Redis buffering.
- **For streaming**: Log to `stream` channel and notify users via `Broadcast`.
exec().exec() calls in app/Console/Commands.app/Services/SystemCommand.SystemCommand to Laravel’s container bindings.How can I help you explore Laravel packages today?