Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Files and I/O

PHP_SAPI and php_sapi_name()

Reference for PHP_SAPI and php_sapi_name(): detect whether code runs on the command line or under a web server, with values like cli, fpm-fcgi and apache2handler.

SAPI stands for Server API: the interface between PHP and whatever is running it. The same PHP engine can be started by a web server, by a FastCGI manager, or by you in a terminal. The constant PHP_SAPI and the function php_sapi_name() tell you which one is active, as a lowercase string.

Knowing the SAPI lets a script decide whether it should print plain text or HTML, whether $_SERVER['REQUEST_URI'] exists, or whether it may read from standard input.

PHP
<?php
if (PHP_SAPI === 'cli') {
    echo "Running in a terminal\n";
}

Try it

PHP Which SAPI is this?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP One script, two output styles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
PHP_SAPI: string
php_sapi_name(): string|false

Common values:

Value Meaning
cli Command-line interpreter (terminal, cron jobs, our examples).
cli-server The built-in development server started with php -S.
fpm-fcgi PHP-FPM, the usual setup behind nginx.
apache2handler PHP as an Apache module.
cgi-fcgi CGI or FastCGI.
phpdbg The phpdbg debugger.
embed PHP embedded in another program.

Return value: the lowercase SAPI name. php_sapi_name() is documented to return false if it cannot be determined.

Errors / Exceptions: none.

Usage notes

  • Prefer the constant. PHP_SAPI is available everywhere without a function call and cannot be shadowed.
  • Use === against a list. Several values behave like a web server, so test for what you need ('cli') instead of enumerating every web SAPI.
  • Environment differences in the CLI: no $_SERVER['REQUEST_URI'], no cookies or sessions in the usual sense, STDIN/STDOUT/STDERR constants exist, and max_execution_time defaults to 0 (unlimited).
  • Guard web-only calls. header() and setcookie() do nothing useful in the CLI, and http_response_code() returns false there.
  • cli-server is not production. If your code checks PHP_SAPI === 'cli', requests handled by php -S will not match, because the value is cli-server.
  • Do not use it for security. It describes the runtime only; it cannot prove who is calling.
  • Entry points: frameworks use this check to choose between a console kernel and an HTTP kernel.
  • Related constants: PHP_OS, PHP_OS_FAMILY and PHP_VERSION describe the platform and version.