I have a PHP script that needs to determine if it's been executed via the command-line or via HTTP, primarily for output-formatting purposes. What's the canonical way of doing this? I had thought it was to inspect SERVER['argc']
, but it turns out this is populated, even when using the 'Apache 2.0 Handler' server API.
相关问题
- Views base64 encoded blob in HTML with PHP
- Angular RxJS mergeMap types
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
I think
will not be populated from the CLI.
Also, all the HTTP_* keys in the $_SERVER superglobal won't be populated from the CLI, or do it the right way hop just mentioned :-)
The documentation page for
php_sapi
_name clearly states how it works:I'm not sure why hop doesn't think that PHP is for serious programmers (I'm a serious programmer, and I use PHP daily), but if he wants to help clarify the documentation then perhaps he can audit all possible web servers that PHP can run on and determine the names of all possible interface types for each server. Just make sure to keep that list updated as new web servers and interfaces are added.
Also, Bobby said:
The description for the example states:
Here is Drupal 7 implementation: drupal_is_cli():
However Drupal 8 recommends using
PHP_SAPI === 'cli'
This will always work. (If the PHP version is 4.2.0 or higher)
Which makes it easy to use at the top of your scripts:
Use the
php_sapi_name()
function.Here are some relevant notes from the docs:
In PHP >= 4.2.0, there is also a predefined constant,
PHP_SAPI
, that has the same value asphp_sapi_name()
.