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 if (PHP_SAPI === 'cli') { echo "Running in a terminal\n"; }
Try it
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.
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_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_SAPIis 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/STDERRconstants exist, andmax_execution_timedefaults to 0 (unlimited). - Guard web-only calls.
header()andsetcookie()do nothing useful in the CLI, andhttp_response_code()returnsfalsethere. cli-serveris not production. If your code checksPHP_SAPI === 'cli', requests handled byphp -Swill not match, because the value iscli-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_FAMILYandPHP_VERSIONdescribe the platform and version.