How to execute PHP scripts on the command line

In PHP, there is a provision for one to successfully execute PHP codes on the command prompt and terminal. To do this, you should do the following.

  1. You must have successfully installed PHP, either stand-alone or in a bundle, and it must be working. To check if it is installed and is the right version, change the directory into the folder where you installed it, like c:/php, and use the following command on your terminal or cmd:
php -v

If you don’t have PHP installed, you can install it as shown below.

On Windows

  • Download it from the official site.
  • Extract the file and store it in a folder, preferably named php, in your C just like so: c:/php
  • Next, place this folder in your environment variable path so that it can be recognized by the command line.

On Linux

To install on Linux, use the command:

apt-get install php5-common libapache2-mod-php5 php5-cli

You can change the php5 to your version of choice.

On MAC

You can run the command below on your terminal to install PHP.

curl -s https://php-osx.liip.ch/install.sh | bash -s 7.3

Now that you have PHP installed and running, we can execute our scripts on the command line or terminal.

Executing your scripts

  • First, you create a PHP file like this one:

file_name.php, prog1.php

  • Next, head to your terminal or command prompt and change the directory into the folder containing your PHP files. Let’s say something like this:

D:\php_project

  • Lastly, enter the following command into your cmd or terminal to run the script file named prog1.php:
php prog1.php

The complete code to run our sample script will be as follows.

D:\php_project\php prog1.php

And with that, you have successfully run your PHP script on the command line or terminal, depending on which you use.

Let’s see the image of the execution of my sample prog1.php script on my cmd.

One last thing: you can also start your development server on the cmd and see your code run on the browser. To do that, enter this code in your command line or terminal.

php -S localhost:port -t your_folder/

Where your_folder stands for the folder containing the php code to be executed.

You should have something like the image below if you have your browser and cmd opened up.