How to distinguish command-line and web-server invocation?

PhpCommand Line-Interface

Php Problem Overview


Is there a way to distinguish if a script was invoked from the command line or by the web server?

(See https://stackoverflow.com/questions/173851/what-is-the-canonical-way-to-determine-commandline-vs-http-execution-of-a-php-s for best answer and more detailed discussion - didn't find that one before posting)


I have a (non-production) server with Apache 2.2.10 and PHP 5.2.6. On it, in a web-accessible directory is my PHP script, maintenance_tasks.php. I would like to invoke this script from the command line or through a HTTP request (by opening in a browser). Is there some variable that allows me to reliably determine how script is invoked?

(I already tackled the issues of different views for each type of invocation and HTTP response timeout, just looking for a way of telling the two invocation types apart)

I'll be trying different things and add my findings below.

Duplicate: https://stackoverflow.com/questions/173851/what-is-the-canonical-way-to-determine-commandline-vs-http-execution-of-a-php-s

Php Solutions


Solution 1 - Php

If called from command line, the server variable HTTP_USER_AGENT is not set. I use this constant to define, whether the script is called from command line or not:

define("CLI", !isset($_SERVER['HTTP_USER_AGENT']));

UPDATE: Since this answer is still marked as the 'correct' one, I'd like to revise my statement - relying on the "User-Agent" header can be problematic, since it's a user-defined value.

Please use php_sapi_name() == 'cli' or PHP_SAPI == 'cli', as suggested by Eugene/cam8001 in the comments.

Thanks for pointing this out!

Solution 2 - Php

I've compared the $_SERVER superglobal in both invocations. It seems that $_SERVER['argc'] (i.e. number of arguments passed to the script) is only set when running from shell/command line:

<?php
if (isset($_SERVER['argc'])) {
    define('CLI', true);
} else {
    define('CLI', false);
}

That seems to work both on Linux and Windows hosts. (First I thought about checking for some of the environment variables, but those are different for every operating system. Also, all the $_SERVER['HTTP_*'] headers are missing in the CLI version, but I'm not sure if that's reliable enough.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPiskvor left the buildingView Question on Stackoverflow
Solution 1 - PhpNuramonView Answer on Stackoverflow
Solution 2 - PhpPiskvor left the buildingView Answer on Stackoverflow