PHP CLI & Environment: Your Secret Command Center 🎮
Imagine your computer is like a smart house. Most people only use the front door (the browser). But there’s a secret back door that lets you control EVERYTHING directly. That’s the CLI—your command line superpower!
🏠The Big Picture: What is CLI?
Think of PHP like a chef. Usually, this chef works in a restaurant (web server) making dishes (web pages) for customers (browsers).
But what if you want the chef to cook just for YOU, in YOUR kitchen, following YOUR direct orders?
That’s CLI! You talk directly to PHP. No restaurant. No waiters. Just you and the chef.
graph TD A["You Type Command"] --> B["PHP CLI Reads It"] B --> C["PHP Does the Work"] C --> D["Shows Result in Terminal"]
🚀 1. CLI Basics: Your First Commands
What is CLI?
CLI = Command Line Interface
It’s a text-based way to run PHP scripts. No browser needed!
How to Run a PHP Script
// save this as hello.php
<?php
echo "Hello from CLI!";
Run it in your terminal:
php hello.php
Output:
Hello from CLI!
Why Use CLI?
| Web PHP | CLI PHP |
|---|---|
| Runs in browser | Runs in terminal |
| Has time limits | Can run forever |
| For websites | For tasks & tools |
| Needs web server | Just needs PHP |
Real-Life Uses
- đź“§ Sending bulk emails
- 🔄 Database backups
- 📊 Processing data files
- ⏰ Scheduled tasks (cron jobs)
📦 2. CLI Arguments: Passing Information
The Analogy
Imagine ordering pizza by phone:
- “I want a large pizza with pepperoni and mushrooms”
Those details are arguments! You’re passing information to the pizza shop.
How Arguments Work
// save as greet.php
<?php
// $argv holds all arguments
// $argv[0] is the script name
// $argv[1], [2]... are your inputs
$name = $argv[1] ?? 'Friend';
echo "Hello, $name!";
Run it:
php greet.php Alice
Output:
Hello, Alice!
Multiple Arguments
// calculator.php
<?php
$num1 = $argv[1] ?? 0;
$num2 = $argv[2] ?? 0;
$sum = $num1 + $num2;
echo "$num1 + $num2 = $sum";
Run it:
php calculator.php 5 3
Output:
5 + 3 = 8
The Magic Variables
| Variable | What It Holds |
|---|---|
$argv |
Array of all arguments |
$argc |
Count of arguments |
<?php
echo "You passed $argc arguments:\n";
print_r($argv);
đź’¬ 3. CLI Input and Output
Output: Talking TO the User
echo - Simple output
<?php
echo "Hello World!";
fwrite + STDOUT - Direct to terminal
<?php
fwrite(STDOUT, "Important message!\n");
fwrite + STDERR - For errors
<?php
fwrite(STDERR, "Oops! Something broke!\n");
The Three Streams
graph LR A["STDIN"] -->|Input| B["Your Script"] B -->|Output| C["STDOUT"] B -->|Errors| D["STDERR"]
| Stream | Purpose | Example |
|---|---|---|
| STDIN | Keyboard input | User typing |
| STDOUT | Normal output | Results |
| STDERR | Error messages | Warnings |
Input: Listening to the User
Reading a single line:
<?php
echo "What's your name? ";
$name = trim(fgets(STDIN));
echo "Nice to meet you, $name!";
Interactive Example:
<?php
echo "Enter a number: ";
$num = (int) trim(fgets(STDIN));
echo "Double is: " . ($num * 2);
🚦 4. CLI Exit Codes: The Secret Signals
The Analogy
Imagine a doctor checking on a patient:
- Thumbs up (0) = “All healthy!”
- Thumbs down (1+) = “Something’s wrong!”
Exit codes work the same way!
How Exit Codes Work
<?php
// Success - everything went well
exit(0);
// Error - something failed
exit(1);
Checking Exit Codes (in bash)
php myscript.php
echo $? # Shows the exit code
Common Exit Codes
| Code | Meaning |
|---|---|
| 0 | Success! All good |
| 1 | General error |
| 2 | Misuse of command |
| 126 | Permission denied |
| 127 | Command not found |
Practical Example
// backup.php
<?php
$file = $argv[1] ?? null;
if (!$file) {
fwrite(STDERR, "Error: No file!\n");
exit(1);
}
if (!file_exists($file)) {
fwrite(STDERR, "File not found!\n");
exit(2);
}
// Do backup...
echo "Backup complete!\n";
exit(0);
Chaining Commands
php backup.php data.txt && echo "Success!"
# "Success!" only shows if exit code is 0
🌍 5. Environment Variables: Hidden Settings
The Analogy
Think of a spy movie. The spy has secret information stored in a hidden pocket—nobody can see it, but the spy can use it anytime.
Environment variables are like that hidden pocket!
What Are They?
They’re key-value pairs stored in your system:
DATABASE_HOST=localhost
API_KEY=secret123
DEBUG_MODE=true
Reading Environment Variables
Using getenv():
<?php
$dbHost = getenv('DATABASE_HOST');
echo "Connecting to: $dbHost";
Using $_ENV:
<?php
$apiKey = $_ENV['API_KEY'] ?? 'not set';
echo "API Key: $apiKey";
Using $_SERVER:
<?php
$path = $_SERVER['PATH'];
echo "System PATH: $path";
Setting Variables (in terminal)
Linux/Mac:
export MY_VAR="Hello"
php script.php
Windows:
set MY_VAR=Hello
php script.php
Inline (one command):
MY_VAR="Hello" php script.php
The .env Pattern
Many apps use a .env file:
# .env file
DB_HOST=localhost
DB_USER=admin
DB_PASS=secret
<?php
// Load .env (simple version)
$lines = file('.env', FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
if (strpos($line, '=') !== false) {
putenv($line);
}
}
echo getenv('DB_HOST'); // localhost
Why Use Environment Variables?
| Hardcoded | Environment Variable |
|---|---|
$pass = "secret123" |
$pass = getenv('DB_PASS') |
| Everyone sees it | Hidden & secure |
| Same everywhere | Different per server |
| Hard to change | Easy to change |
🎯 Putting It All Together
Here’s a complete CLI tool using everything we learned:
#!/usr/bin/env php
<?php
// task-runner.php
// Get environment settings
$debug = getenv('DEBUG') === 'true';
// Check arguments
if ($argc < 2) {
fwrite(STDERR, "Usage: php task-runner.php <task>\n");
exit(1);
}
$task = $argv[1];
// Show debug info
if ($debug) {
fwrite(STDOUT, "[DEBUG] Running: $task\n");
}
// Run the task
switch ($task) {
case 'backup':
echo "Backing up...\n";
// do backup
exit(0);
case 'clean':
echo "Cleaning...\n";
// do cleanup
exit(0);
default:
fwrite(STDERR, "Unknown task: $task\n");
exit(2);
}
Run it:
DEBUG=true php task-runner.php backup
🌟 Quick Summary
graph TD A["CLI Basics"] --> B["Run scripts in terminal"] C["Arguments"] --> D["$argv and $argc"] E["Input/Output"] --> F["STDIN, STDOUT, STDERR"] G["Exit Codes"] --> H["0 = success, 1+ = error"] I["Env Variables"] --> J["getenv and $_ENV"]
| Concept | Key Takeaway |
|---|---|
| CLI Basics | php script.php runs directly |
| Arguments | $argv[1] gets first argument |
| Input | fgets(STDIN) reads user input |
| Output | echo or fwrite(STDOUT) |
| Errors | fwrite(STDERR) for errors |
| Exit Codes | exit(0) = success |
| Env Vars | getenv('VAR') reads them |
🚀 You Did It!
You now have the secret keys to PHP’s command line!
No more being limited to web pages. You can now:
- âś… Run scripts directly
- âś… Pass arguments like a pro
- âś… Handle input and output
- âś… Signal success or failure
- âś… Use secure environment variables
The command line is your new superpower. Go build something amazing! 🎉
