php_sapi_name
php_sapi_name()
Returns the name of the interface PHP runs through: “cli” on the command line, “apache2handler” as an Apache module, “fpm-fcgi” under PHP-FPM, “cgi-fcgi” through FastCGI. The constant PHP_SAPI has the same value.
Examples
var_dump(php_sapi_name() === PHP_SAPI); // bool(true)
// a script only for the command line or cron
function command_line_only() {
if (php_sapi_name() !== "cli") {
http_response_code(403);
exit("Run it from the command line.");
}
}
// command_line_only();
// the line ending by environment
$eol = PHP_SAPI === "cli" ? PHP_EOL : "<br>";
Things to watch out for
- The built-in server (php -S) returns “cli-server”, not “cli”.
- The command line lacks the request data: $_SERVER["HTTP_HOST"], $_SERVER["REQUEST_URI"], cookies, the session cookie. A cron script must not rely on them.
- It is safer to keep cron scripts outside the public folder of the website. Checking php_sapi_name() is an extra safeguard.
- On the command line max_execution_time is 0 and often a different php.ini than for the web is used.
Related functions:
phpversion()
getenv()
http_response_code()
getopt()