Detect CLI (Command Line Interface) using PHP

This post shows you how to identify Command Line Interface in PHP.

The main focus of CLI SAPI is for developing shell applications with PHP. However, you may want to create some applications which could be run, at the same time, using CLI and another SAPI (eg: web server).

To detect CLI, you can use this function:

function is_cli() : bool {
   return (php_sapi_name() === 'cli');

Let’s say we want to create a simple application that reads data from user input and prints a message. We want this to be available for both, CLI and Web. On the web version of our application, we want to read the data as a GET parameter, and on the CLI version we want to read data from STDIN. Using the function above, we can do this as follows:

if(!is_cli()) {
   echo "Hello, " . $_GET["name"];
} else {
   $name = readline("Enter you name: ");
   echo "Hello, " . $name;

Note: this is a simple example. In a real-case application, you must sanitize user input.

If you need a reliable Dedicated Server or VPS, you should definitely try InterServer Hosting. You can test InterServer for 1 Penny, for the first month, using this coupon code: WSG1PENNY.