We may want to restrict the execution of a PHP file to CLI only.

For example, when running a PHP file as part of a Bash automation script.

In this case, we would like to prevent the PHP file from being accessed and run through the browser.

To apply such a restriction, we can use the following code snippet:

// Allow this PHP script to run via CLI only.
if ( 'cli' !== php_sapi_name() ) {
	exit;
}

This code detects the interface from which the request is coming. If it didn’t come from the CLI, it will stop the rest of the script from executing (using the exit function).

We’ll probably want to place this code snippet at the top of the file (after the top comments) so that this check is executed before the rest of the file.