How to run a PHP script from the command line?
Open the terminal and use the php command (PHP CLI) with the file name. You do not need a web server for this.
php hello.php
Here is the script. The values you type after the file name are available in the $argv array. The first item, $argv[0], is the file name.
<?php
echo "Hello " . ($argv[1] ?? "World") . PHP_EOL;
?>
Now run the command with a name:
php hello.php Robin
Output:
Tutorials Class - Output Window
Hello Robin
Some more useful commands:
| Command | What it does |
|---|---|
php -v | Shows the PHP version |
php -r "echo 2+2;" | Runs a small piece of code directly |
php -l file.php | Checks the file for syntax errors |
php -m | Lists the installed PHP modules |
php -S localhost:8000 | Starts the built-in web server for testing |
The older form php -f file.php also works and gives the same result.
Learn more about the similar topics:
| Tutorials |
|---|
| PHP Introduction |
| PHP Terminology |
| PHP Installation |
| PHP Syntax |
| PHP Comments |
| PHP exit() Function |
| Exercises & Assignments |
|---|
| Write a program to print “Hello World” using echo |
| Simple Tips for PHP Beginners |
| Experiment with Basic PHP Syntax Errors |
| Using phpinfo() – Display PHP Configuration & Modules |