PHP Command Line Scripting

Did you know PHP is not just for web development? You can run PHP scripts directly from the terminal for automation, cron jobs, and system administration tasks. This is known as PHP CLI (Command Line Interface). πŸš€


πŸ“Œ Why Use PHP from the Command Line?

  • βœ… Automate tasks and scripts without a browser.
  • βœ… Execute PHP code quickly for testing.
  • βœ… Use PHP for server maintenance and cron jobs.
  • βœ… Build interactive command-line applications.

πŸ”Ή How to Run PHP from the Command Line

To check if PHP CLI is installed, open a terminal and type:

php -v

If PHP is installed, you’ll see the version details.

πŸ“ Example 1: Running a Simple PHP Script

Create a file script.php with the following content:

<?php
echo "Hello from the command line! πŸš€\n";
?>

Try It Now

Now, run the script in the terminal:

php script.php

It will output:

Hello from the command line! πŸš€

πŸ“ Example 2: Accepting User Input

PHP CLI can read user input using fgets(STDIN).

<?php
echo "Enter your name: ";
$name = trim(fgets(STDIN)); // Read user input
echo "Hello, $name! πŸŽ‰\n";
?>

Try It Now

Run the script:

php input.php

It will prompt for input:

Enter your name: John
Hello, John! πŸŽ‰

πŸ“ Example 3: Using Command-Line Arguments

PHP CLI can receive arguments using $argv.

<?php
if ($argc > 1) {
    echo "Hello, $argv[1]! πŸŽ‰\n";
} else {
    echo "Usage: php script.php [your name]\n";
}
?>

Try It Now

Run it with an argument:

php script.php Alice

Output:

Hello, Alice! πŸŽ‰

🎯 Summary

  • βœ… PHP CLI lets you run PHP scripts in the terminal.
  • βœ… You can accept user input using fgets(STDIN).
  • βœ… Command-line arguments are stored in $argv.
  • βœ… Useful for automation, cron jobs, and scripting.

πŸš€ Next Steps

Try creating a CLI calculator, task manager, or automation script using PHP CLI. Happy coding! πŸŽ‰