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 which 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.

Last modified: May 12, 2021

Author

Comments

Write a Reply or Comment

Your email address will not be published.