Run PHP Script From Command Line

A PHP script can be executed from the command line even without having any web server software installed.

To run the PHP script from the command line you should just have a PHP CLI (PHP Command Line Interface) installed on your system.

This note shows how to run the PHP script from the command line and how to get the PHP CLI installed on Windows, Linux and MacOS.

Cool Tip: How to find the location of the php.ini file! Read more →

Run PHP Script From Command Line

Let’s say we have a script.php file with the simplest PHP code:

<?php echo "Hello World!"; ?>

To run the script.php from the command line, execute:

$ php script.php
- sample output -
Hello World!

Install PHP CLI

The messages as follows mean you are missing the php-cli on your system and should install it first to be able to run the PHP scripts from the command line:

‘php’ is not recognized as an internal or external command,
operable program or batch file
– or –
php: command not found

To check whether php-cli is installed, execute:

$ php -v
- sample output -
PHP 7.4.3 (cli) (built: Nov 25 2021 23:16:22) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies

MacOS comes with PHP installed out of the box.

To install php-cli on Linux:

$ sudo apt install php-cli

To install PHP on Windows, download a ZIP package with the required version, extract it to C:\php and add this folder to a %PATH% environment variable.

For this, press the ⊞ Win keybutton to open the start menu and type in envi to search for “Edit the system environment variables” or “Edit environment variables for your account” links.

Start the editor, search for the Path variable name, click on “Edit” and add C:\php.

To create the default PHP’s configuration file, that is initially missing on Windows, copy C:\php\php.ini-development to C:\php\php.ini:

C:\> copy C:\php\php.ini-development C:\php\php.ini

Finally, after getting the PHP installed, you should be able to run the script.php from the command line without any issues.

C:\> php script.php
- sample output -
Hello World!
Was it useful? Share this post with the world!

One Reply to “Run PHP Script From Command Line”

  1. can i use php syntax without using the file?

Leave a Reply