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"; ?>
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"; ?>
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"; } ?>
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! π