PHP can be used to create command-line scripts (CLI) much like shell scripts.
#!/usr/bin/env php
<?php
echo "Hello World\n";Make executable:
chmod +x hello.php
./hello.phpOr run directly:
php hello.php<?php
$name = $argv[1] ?? 'Guest';
echo "Hello {$name}\n";Run:
php greet.php JohnOutput:
Hello John
<?php
require __DIR__ . '/bootstrap.php';
$userRepository = new UserRepository(
Database::getConnection()
);
$users = $userRepository->findAll();
foreach ($users as $user) {
echo "{$user->id} {$user->email}\n";
}Run:
php scripts/list-users.phpFor multiple commands:
interface Command
{
public function execute(array $args): int;
}class CreateUserCommand implements Command
{
public function execute(array $args): int
{
echo "Creating user...\n";
return 0;
}
}Dispatcher:
$commands = [
'create-user' => new CreateUserCommand(),
];
$commandName = $argv[1] ?? '';
if (!isset($commands[$commandName])) {
exit("Unknown command\n");
}
exit(
$commands[$commandName]->execute(
array_slice($argv, 2)
)
);Usage:
php app.php create-userFor professional CLI applications, use Symfony Console.
Install:
composer require symfony/consoleExample:
class ListUsersCommand extends Command
{
protected static $defaultName = 'users:list';
protected function execute(
InputInterface $input,
OutputInterface $output
): int {
$output->writeln('Listing users');
return Command::SUCCESS;
}
}Run:
php bin/console users:listBenefits:
- Options (
--email=test@example.com) - Arguments validation
- Tables and formatted output
- Progress bars
- Interactive prompts
- Auto-generated help
Typical structure:
project/
├── bin/
│ └── console
├── src/
│ ├── Command/
│ │ ├── ListUsersCommand.php
│ │ └── CreateUserCommand.php
│ ├── Repository/
│ ├── Entity/
│ └── Service/
└── composer.json
For anything beyond a couple of scripts, Symfony Console is the standard approach in modern PHP applications.