Check if PHP is running from the command-line

When running PHP from the command-line interface, the availability of some variables and functionality may or may not be available. Case in point, when running command-line PHP sessions are not available and $_SESSION is undefined. When you’re on the command-line there’s also the possibility that you want to use the passed command-line arguments that exist in $_SERVER['argc'] and $_SERVER['argv'].

When you’re using a script that is being served by both a web server as well as run from the command-line, things can get tricky so you’ll want to be able to determine which environment you’re running in. This is one of those problems that has quite a few potential answers, like interrogating the user agent or checking for the existence of the aforementioned $_SESSION variable. Both could be considered flawed because the user agent is unreliable as it’s set by the user and/or their browser so it could actually be empty and sessions could simply be disabled and not just unavailable because we’re on the CLI.

Your best bet as of PHP 4.0.1 is to use php_sapi_name() to determine which interface you are using:

if (php_sapi_name() == 'cli')
{
	echo 'Hello CLI!'
}
else
{
	echo 'Hello World!' // or web server ;)
}

The function php_sapi_name() can return a variety of different values based on your web server and configuration, but will always return cli when running from the command-line. Additionally, if you’re running PHP 4.2 or above (if not, consider upgrading immediately) you can use the constant PHP_SAPI which holds the same set of values as returned by php_sapi_name().

It’s most likely negligible but I ran some local tests and using the constant PHP_SAPI consistently outperformed the function php_sapi_name() as it only took a third of the time to execute over 1 million iterations.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.