PHP Command Line Interface

PHP 120 views Dec 22, 2025 2 min read

What is PHP CLI?

PHP CLI (Command Line Interface) allows you to run PHP scripts directly from the command line or terminal, without a web server. It is commonly used for automation, cron jobs, background tasks, and scripts.


Why Use PHP CLI?

  • No web server required

  • Faster execution

  • Ideal for automation & cron jobs

  • Easy debugging

  • Used by frameworks (Laravel Artisan, Symfony Console)


Check PHP CLI Installation

php -v

If PHP CLI is installed, it will show the PHP version.


Running a PHP Script from CLI

Create a file test.php:

<?php echo "Hello PHP CLI";

Run it:

php test.php

PHP CLI vs Web PHP

FeaturePHP CLIWeb PHP
ExecutionTerminalBrowser
ServerNot requiredRequired
OutputTextHTML
Use caseAutomationWeb apps

Command Line Arguments

Access arguments using $argv.

<?php echo $argv[1];

Run:

php script.php hello

Getting Argument Count

echo $argc;

Reading User Input

$input = trim(fgets(STDIN)); echo "You entered: $input";

Creating Executable PHP Scripts (Linux/macOS)

#!/usr/bin/php <?php echo "Executable script";

Make executable:

chmod +x script.php ./script.php

PHP CLI for Cron Jobs

Cron Job Example

* * * * * php /path/to/script.php

Environment Variables in CLI

echo getenv("PATH");

CLI Colors (Basic)

echo "\033[32mSuccess\033[0m";

PHP Built-in CLI Server

php -S localhost:8000

Common CLI Use Cases

  • Scheduled tasks

  • Database backups

  • Data processing

  • Email scripts

  • Queue workers


Best Practices

  • Handle errors properly

  • Validate CLI arguments

  • Log output to files

  • Use exit codes

  • Secure sensitive data


Conclusion

PHP CLI is a powerful tool for automation and backend tasks. Mastering PHP CLI allows developers to create efficient scripts beyond traditional web applications.

Some advanced sections are available for Registered Members
Share this Post
🚀 Want to Test Your Knowledge?

Take quizzes related to this topic and see where you stand!

Start Quiz Now
Back to Tutorials