PHP Command-line Interface (CLI)

Vaqar
2 min readMay 9, 2019

--

PHP Command-line Interface

A PHP command-line interface is great for a quick check of PHP configurations or a small syntax code testing. It saves times compared to creating a PHP webpage and running it on a webserver.

There are many advanced uses of PHP CLI but let’s just keep it simple and stupid CLI usage.

PHP Interactive Shell

To invoke PHP interactive shell run

$php -a

A one-line PHP code can be tested on PHP interactive shell. Another great use is to check your Regular Expression syntax. Store search string in a variable and making small changes in RegEx and execute preg_match, until you get desired output.

To exit the PHP interactive shell simply run CTL+C.

I have copied and pasted functions in PHP command-line interactive shell. Very handy to test lines of code while coding. While you are in terminal use vi, vim or nano to edit and make small changes in your script files.

Checking PHP Configurations | php.ini

A simple echo phpinfo() in webserver or command-line shell will display all PHP configurations. Instead, try running this in the command line:

$php -i

If you have two different PHP ini files for webserver and CLI, specify php.ini location to see it’s configuration.

php -c /etc/php/apache2/php.ini -i

How to find PHP Configuration file php.ini

A very simple command can help you find locations of all PHP ini files and the path of currently loaded php.ini configuration file. Simply run

$php — ini

Its $php followed by a space and two hyphens (-) without any space in between.

How to check PHP script output in the command line

Simply direct the script to PHP interpreter which will execute script file and output result on terminal. For example, run this command in the terminal to execute a PHP script located in /home/username directory

$/usr/bin/php /home/username/scriptfile.php

PHP Command line Global Regular Expression Print (grep)

Use grep to look for specific output as sometimes you get a massive amount of data in the output. For instance when you run $php -i and only want to see ini location type this in the command line

$php -i | grep ‘php.ini’

In my case it outputs

Configuration File (php.ini) Path => /etc/php/7.0/cli

Loaded Configuration File => /etc/php/7.0/cli/php.ini

In this command, we have used | pipe to direct PHP output to grep. grep looks for ‘php.ini’ in that output and returns matching lines.

Similarly, you can check if mysqli is loaded or search for any specific strings in PHP output.

$php -i | grep ‘mysqli’

Hope you find it useful and if you know any other usage do share, thanks.

--

--