PHP - Building Command-Line Applications (CLI) with PHP
Introduction
PHP is widely recognized as a server-side scripting language used for developing dynamic websites and web applications. However, PHP is also capable of creating powerful command-line applications through its Command Line Interface (CLI). PHP CLI enables developers to execute PHP scripts directly from a terminal or command prompt without requiring a web server such as Apache or Nginx. This makes PHP suitable for automation, maintenance tasks, data processing, system administration, scheduled jobs, and utility development.
Unlike web applications that interact with users through a browser, CLI applications communicate with users through text commands and terminal output. Many popular PHP frameworks, including Laravel and Symfony, provide command-line tools that simplify project management and application development.
What is PHP CLI?
PHP CLI (Command Line Interface) is a version of PHP designed specifically for running scripts from the terminal. It allows developers to execute PHP code directly without involving a web browser.
Example command:
php script.php
In this example:
-
phplaunches the PHP interpreter. -
script.phpis the PHP file to execute.
PHP CLI is commonly used for:
-
Running scheduled tasks
-
File processing
-
Database maintenance
-
Data migration
-
Backup automation
-
Creating developer tools
-
System monitoring
-
Generating reports
Checking PHP CLI Installation
Before creating CLI applications, verify that PHP is installed.
For Windows:
php -v
For Linux/macOS:
php --version
Example output:
PHP 8.3.0 (cli)
Copyright (c) The PHP Group
Zend Engine v4.3.0
If the version appears, PHP CLI is correctly installed.
Creating Your First CLI Application
Create a file named:
hello.php
Code:
<?php
echo "Welcome to PHP CLI!\n";
Run it:
php hello.php
Output:
Welcome to PHP CLI!
The \n inserts a new line in terminal output.
Reading User Input
CLI applications often require user interaction.
Example:
<?php
echo "Enter your name: ";
$name = trim(fgets(STDIN));
echo "Hello, $name\n";
Execution:
Enter your name:
John
Hello, John
Explanation:
-
STDINrepresents keyboard input. -
fgets()reads input. -
trim()removes extra spaces and newline characters.
Command-Line Arguments
Arguments allow users to pass information while executing the script.
Example:
php greet.php Rahul
Code:
<?php
echo "Hello " . $argv[1];
Output:
Hello Rahul
Explanation:
-
$argvstores command-line arguments. -
$argv[0]contains the script name. -
$argv[1]contains the first argument. -
$argccontains the total number of arguments.
Example:
<?php
echo "Total Arguments: $argc\n";
Command:
php test.php Apple Orange Mango
Output:
Total Arguments: 4
Validating Arguments
Always validate input before using it.
Example:
<?php
if ($argc < 2) {
echo "Please provide your name.\n";
exit;
}
echo "Hello " . $argv[1];
Execution:
php greet.php
Output:
Please provide your name.
Working with Options
CLI tools often use options.
Example:
php app.php --name=David
Code:
<?php
$options = getopt("", ["name:"]);
echo "Hello " . $options['name'];
Output:
Hello David
The getopt() function simplifies option handling.
Creating Interactive Menus
CLI programs often display menus.
Example:
<?php
echo "1. Add User\n";
echo "2. Delete User\n";
echo "3. Exit\n";
echo "Choose an option: ";
$choice = trim(fgets(STDIN));
switch ($choice) {
case 1:
echo "Adding User...";
break;
case 2:
echo "Deleting User...";
break;
case 3:
echo "Goodbye!";
break;
default:
echo "Invalid Option";
}
Output:
1. Add User
2. Delete User
3. Exit
Choose an option:
2
Deleting User...
Creating Loops in CLI Programs
Many CLI applications continue running until the user exits.
Example:
<?php
while (true) {
echo "Type quit to exit: ";
$input = trim(fgets(STDIN));
if ($input == "quit") {
break;
}
echo "You typed: $input\n";
}
Output:
Type quit to exit:
PHP
You typed: PHP
Type quit to exit:
quit
Reading Files from CLI
Example:
<?php
$content = file_get_contents("data.txt");
echo $content;
This reads the contents of a file and displays them in the terminal.
Writing Files
Example:
<?php
file_put_contents("log.txt", "Application Started\n");
This creates or updates a log file.
Displaying Progress
Long-running scripts should provide progress information.
Example:
<?php
for($i=1; $i<=10; $i++){
echo "Processing $i\n";
sleep(1);
}
Output:
Processing 1
Processing 2
Processing 3
...
Processing 10
Using Exit Codes
Exit codes indicate success or failure.
Example:
<?php
if(file_exists("data.txt")){
exit(0);
}else{
exit(1);
}
Common exit codes:
| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | General Error |
| 2 | Invalid Usage |
Exit codes are useful when CLI scripts are called by other programs or shell scripts.
Scheduling CLI Applications
CLI scripts can run automatically.
Linux:
Cron Jobs
Example:
0 2 * * * php backup.php
Runs every day at 2:00 AM.
Windows:
Task Scheduler
Schedules PHP scripts to execute automatically.
Building a Simple Calculator
Example:
<?php
echo "Enter First Number: ";
$a = trim(fgets(STDIN));
echo "Enter Second Number: ";
$b = trim(fgets(STDIN));
echo "Sum = " . ($a + $b);
Output:
Enter First Number:
15
Enter Second Number:
25
Sum = 40
Building a Password Generator
Example:
<?php
$characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$password = "";
for($i=0;$i<10;$i++){
$password .= $characters[rand(0, strlen($characters)-1)];
}
echo $password;
Possible output:
Ab9Kd4LpQ1
Logging Errors
Example:
<?php
$error = "Database connection failed";
file_put_contents(
"error.log",
$error . PHP_EOL,
FILE_APPEND
);
Logs help monitor application issues.
Organizing CLI Projects
A recommended structure:
project/
│
├── app/
│ ├── Commands/
│ ├── Services/
│ └── Helpers/
│
├── logs/
│
├── config/
│
├── vendor/
│
└── console.php
This keeps the application organized and scalable.
Advantages of PHP CLI
-
Does not require a web server.
-
Executes quickly for automation tasks.
-
Ideal for scheduled jobs and batch processing.
-
Easily integrates with shell scripts.
-
Suitable for data migration and backups.
-
Supports interactive user input.
-
Uses the same PHP language as web development.
-
Available on Windows, Linux, and macOS.
Limitations
-
No graphical user interface.
-
Less suitable for applications requiring rich visual interaction.
-
Users need basic knowledge of terminal commands.
-
Long-running processes may consume system resources if not managed properly.
Best Practices
-
Validate all user input.
-
Handle errors gracefully using exceptions or checks.
-
Organize code into reusable functions and classes.
-
Log important events and errors.
-
Use meaningful exit codes.
-
Avoid hardcoding file paths and credentials.
-
Display clear usage instructions for commands.
-
Test scripts with different inputs and edge cases.
-
Keep CLI applications modular for easier maintenance.
-
Document available commands and options for users.
Real-World Applications of PHP CLI
-
Automated database backups.
-
Log file analysis.
-
Bulk email processing.
-
Data import and export.
-
Image and document processing.
-
Scheduled report generation.
-
File synchronization.
-
System health monitoring.
-
Deployment and maintenance scripts.
-
Batch processing of large datasets.
Conclusion
PHP CLI extends PHP beyond web development by enabling developers to build efficient command-line applications for automation, administration, and data processing. By understanding how to read user input, process command-line arguments, manage files, create interactive menus, schedule tasks, and organize projects, developers can create reliable and maintainable CLI tools. These skills are widely used in modern software development for scripting, deployment, system maintenance, and large-scale automation.