Home / Determine whether PHP is being run via HTTP or CLI

Determine whether PHP is being run via HTTP or CLI

PHP can be run as a webserver module, as a CGI application or from the command line as a CLI script. There is both a function and a PHP constant which allows you to determine whether PHP is being run via HTTP or CLI. This post looks at the function and constant and the possible values, as determined in the PHP 5.2.5 source code.


The PHP function php_sapi_name() takes no arguments returns the interface as a lower case string.

Example usage:

echo php_sapi_name()

This will echo e.g. "apache"


The PHP_SAPI constant provides the same value as the php_sapi_name() function.

Example usage:


This will echo e.g. "apache"

Return values

The values returned by php_sapi_name() and PHP_SAPI can be found in the source code. Unfortunately they are not documented in the PHP documentation, other than in a user comment. To work out all the possible current values I downloaded the latest PHP source code (5.2.5 as at the time of this post) and had a look.

There is a structure called sapi_module_struct which contains, among other things, the name. This can be found referenced throughout the PHP source code as sapi_module.name, and is set by the code in the "sapi" directory of the source code. There are several sub-directories, one for each module/interface type and only one of these will be compiled into PHP depending on the compile time settings.

Looking through this, I worked out the possible current values are:

  • aolserver
  • apache
  • apache2filter
  • apache2handler
  • caudium
  • cgi
  • cgi-fcgi
  • cli
  • Continuity
  • embed
  • isapi
  • milter
  • nsapi
  • phttpd
  • pi3web
  • roxen
  • thttpd
  • tux
  • webjames

These can be found as in the following example for apache/mod_php5.c:

static sapi_module_struct apache_sapi_module = {
  "apache",  /* name */
  "Apache",  /* pretty name */

How to determine if PHP is being run as a CLI

If PHP is being run as a CLI (command line interface) application, then the value returned by php_sapi_name() and PHP_SAPI will be "cli". So you could do something like this:

if(PHP_SAPI == 'cli') {
else {


if(php_sapi_name() == 'cli') {
else {

So if you needed to do something different depening whether PHP is being run via a web server or from the command line, you would use the php_sapi_name() or PHP_SAPI constant as shown in the above examples.