Skip to main content

How to Run a PHP Script from the Terminal

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

PHP is best known for web pages, but it runs from the terminal too, with no web server at all. php <file> runs a script, and the words you type after the file's name reach the script as arguments.

Syntax​

Syntax
php <file> [<arguments>]
PartWhat it does
phpStarts PHP's command-line program.
<file>The script to run, such as hello.php, or a path to it.
<arguments>Optional. Words passed to the script, which it reads from $argv.

The Example​

The example is a one-file script, hello.php, that greets whoever you name on the command line, or the whole world when you name nobody, and says which PHP version ran it.

Prerequisites​

  • PHP. Check it with php --version. This guide uses PHP 8.6.0.

Step 1: Write the Script​

Terminal
mkdir hello-php
cd hello-php

Create hello.php:

hello.php, which takes the name from $argv[1], falling back to world, and echoes a greeting with PHP_VERSION.

hello.php
<?php

$name = $argv[1] ?? 'world';
echo "Hello, {$name}! This is PHP " . PHP_VERSION . ".\n";

$argv lists the command line: the script's name first, then the arguments, so $argv[1] is the first argument. ?? 'world' uses world when there is none, and PHP_VERSION holds the version of PHP that's running.

Step 2: Run It​

Terminal
php hello.php
Output
Hello, world! This is PHP 8.6.0.

Step 3: Pass an Argument​

Terminal
php hello.php Ada
Output
Hello, Ada! This is PHP 8.6.0.

A zsh terminal where php hello.php prints Hello, world! This is PHP 8.6.0. and php hello.php Ada prints Hello, Ada!

The commands and the output are the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out <?php at the topPHP prints the file's text instead of running itStart the file with <?php
Forgetting \n at the end of the textThe next prompt appears on the same lineEnd printed lines with \n
Running the script from another folderPHP can't open itcd into its folder, or give its path

Troubleshooting​

SymptomLikely causeFix
Could not open input file: hello.phpYou're not in the script's folderCheck with pwd, then cd into it
command not found: phpPHP isn't installed, or isn't on your PATHInstall PHP and open a new terminal

FAQ​

Can I run PHP code without a file?​

Yes. php -r 'echo 1 + 1, "\n";' runs the code in the quotes. Leave out the <?php there.

Does the command line use the same settings as a web server?​

Not always. The command-line program can read a different php.ini, and it has no time limit by default. php --ini shows which files it reads.

Conclusion​

php <file> runs a PHP script from the terminal, and $argv holds the words after the file's name, starting at $argv[1].

Additional Resources​