Is there a way to distinguish if a script was invoked from the command line or by the web server?
(See What is the canonical way to determine commandline vs. http execution of a PHP script? 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: What is the canonical way to determine commandline vs. http execution of a PHP script?
To detect if your PHP script is being called via a web client or via CLI, you can use the php_sapi_name function. If you use this simple code: echo php_sapi_name();
A command-line interface (CLI) is a text-based user interface (UI) used to run programs, manage computer files and interact with the computer. Command-line interfaces are also called command-line user interfaces, console user interfaces and character user interfaces.
PHP's Command Line Interface (CLI) allows you to execute PHP scripts when logged in to your server through SSH. ServerPilot installs multiple versions of PHP on your server so there are multiple PHP executables available to run.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With