How to restrict the execution of a PHP script to the command line (detect if running PHP from the CLI)

The function php_sapi_name() and the constant PHP_SAPI both return the type of interface (Server API) that is being used by PHP. They can be used to restrict the execution of a script to the command line, by checking whether the output of the function is equal to cli. You can verify wheter you are running PHP from the CLI or a web server with the following conditional:

<?php

if (php_sapi_name() === 'cli') {
    echo "Executed from command line! \n";
} else {
    echo "Executed from the web browser! \n";
}

Or with the PHP_SAPI constant:

<?php

if(PHP_SAPI == 'cli') {
    echo "Executed from command line! \n";
} else {
    echo "Executed from the web browser! \n";
}

When running from the CLI, it's worht to mention that PHP behaves someway different than when running it  from a web server. These differences should be kept in mind, especially in the case where the same script might be run from both environments.

  • When running a script from a web server, the current working directory is always that of the script itself. The code require("./stuff.inc"); assumes the file is in the same directory as the script. On the command line, the current working directory is the directory you're in when you call the script. Scripts that are going to be called from the command line should always use absolute paths. (Note the magic constants __DIR__ and __FILE__ continue to work as expected, and return the location of the script.)
  • In the event you have enabled the php.ini directive html_errors, it will be ignored on the command line.
  • No output buffering The php.ini directives output_buffering and implicit_flush default to false and true, respectively. Buffering is still available, but must be explicitly enabled, otherwise output will always be displayed in real time.
  • The php.ini directive max_execution_time is set to zero, so scripts will not time out by default (no time limit).
  • A Different php.ini can be loaded during the initialization, so when you are using php from cli it can use different php.ini than web server do. You will be able to identify which file us using by running php --ini.

Happy coding !

This could interest you

Become a more social person