Learn how to determine wheter you are running PHP from the command line or from a web server.

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 !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors