3 Useful Tips Running PHP from the Command Line

In this post, you’ll find 3 useful tips running PHP from the command line. It is assumed that you have PHP 7 install on your computer and PHP has been added to your path.

Let’s get started.

Check PHP version on the terminal

To check the version of PHP is to type the following on the command line.

php -v

This print the version of PHP and some copyright details.

PHP 7.3.1 (cli) (built: Jan  9 2019 22:20:52) ( ZTS MSVC15 (Visual C++ 2017) x64
 )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.1, Copyright (c) 1998-2018 Zend Technologies

Run a PHP file from the terminal

Assuming we have file sayhello.php with the following code:

<?php
// say hello
echo "Hello PHP";
?>

To run the code from the terminal, we simply:

php -f sayhello.php

Output:

Hello PHP

Open up PHP Interactive Shell

The following line code opens PHP Interactive Shell from the command line:

php -a 

Output:

Interactive shell

php >

Since we have open the interactive shell,

Let’s write and run PHP code directly on the shell.

Run PHP code on the Interactive Shell

Type echo date(“Y-m-d H:i:s”); on shell and enter.

php > echo date("Y-m-d H:i:s");

Output:

2019-05-13 09:18:54

Another example: Let assign value to different three variables, $a, $b, $c ( $c contains the addition of $a and $b) and print the result.

php > $a = 1;
php > $b = 3;
php > $c = $a + $b;
php > echo $c;

Output:

3

You can play around with PHP code directly on the interactive shell.

Quit the PHP interactive Shell

To quit the interactive shell, simply quit:

php > quit

Invoke a Web server ( Without Apache or Nginx)

Running a project with the built-in PHP web server:

Simply move to the root of your project or the folder you want to run your project from, and enter the command:

php -S localhost:8000

Assuming we are running a project with the following code on the index.php

<?php 
echo "Welcome to my Website";
?>

And we invoke PHP web server to port 3000:

php -S localhost:3000

We can locate to localhost:3000 on the browser to see the result.

result-running-php-from-the-command-line

Note that you can use any available port of your choice.

Awesome! you just learnt 3 useful tips running PHP from the command line.

Leave a Comment

Your email address will not be published. Required fields are marked *