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:

CommandWhat it does
php -vShows the PHP version
php -r "echo 2+2;"Runs a small piece of code directly
php -l file.phpChecks the file for syntax errors
php -mLists the installed PHP modules
php -S localhost:8000Starts 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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.