I need to determine whether the PHP file is being loaded via cron or command line within the code. How can I do this?
我需要确定是否通过代码中的cron或命令行加载PHP文件。我怎样才能做到这一点?
4 个解决方案
#1
16
If you have control over the cron or command, have you considered passing a command-line argument, and reading it with $_SERVER['argv'][0]
?
如果您可以控制cron或命令,您是否考虑过传递命令行参数,并使用$ _SERVER ['argv'] [0]读取它?
* * * * * /usr/bin/php /path/to/script --cron
In the script:
在脚本中:
<?php
if(isset($_SERVER['argv'][0]) and $_SERVER['argv'][0] == '--cron')
$I_AM_CRON = true;
else
$I_AM_CRON = false;
#2
6
This is one simple way. Certain elements of the $_SERVER
array are only set if called from HTTP. Thus you can:
这是一种简单的方法。仅当从HTTP调用时,才会设置$ _SERVER数组的某些元素。因此你可以:
if(!isset($_SERVER['REQUEST_METHOD'])){
// from cron or command line
}else{
// from HTTP
}
Others include: $_SERVER['HTTP_HOST']
其他包括:$ _SERVER ['HTTP_HOST']
#3
6
The most reliable and exhaustive way to check where your script is run known to me is
检查脚本运行位置的最可靠和详尽的方法是
php_sapi_name()
Neither this nor any of the other listed methods listed here, however, will give you a distinction between "normal" CLI mode, and a cron call. gahooa's command line argument idea is probably the best and most reliable solution.
但是,此处列出的这个或任何其他列出的方法都不会让您区分“正常”CLI模式和cron调用。 gahooa的命令行参数思想可能是最好和最可靠的解决方案。
#4
2
You can check the PHP_SAPI
constant to check if the CLI interpreter is being used:
您可以检查PHP_SAPI常量以检查是否正在使用CLI解释器:
$is_cli= PHP_SAPI == 'cli';
$ is_cli = PHP_SAPI =='cli';
#1
16
If you have control over the cron or command, have you considered passing a command-line argument, and reading it with $_SERVER['argv'][0]
?
如果您可以控制cron或命令,您是否考虑过传递命令行参数,并使用$ _SERVER ['argv'] [0]读取它?
* * * * * /usr/bin/php /path/to/script --cron
In the script:
在脚本中:
<?php
if(isset($_SERVER['argv'][0]) and $_SERVER['argv'][0] == '--cron')
$I_AM_CRON = true;
else
$I_AM_CRON = false;
#2
6
This is one simple way. Certain elements of the $_SERVER
array are only set if called from HTTP. Thus you can:
这是一种简单的方法。仅当从HTTP调用时,才会设置$ _SERVER数组的某些元素。因此你可以:
if(!isset($_SERVER['REQUEST_METHOD'])){
// from cron or command line
}else{
// from HTTP
}
Others include: $_SERVER['HTTP_HOST']
其他包括:$ _SERVER ['HTTP_HOST']
#3
6
The most reliable and exhaustive way to check where your script is run known to me is
检查脚本运行位置的最可靠和详尽的方法是
php_sapi_name()
Neither this nor any of the other listed methods listed here, however, will give you a distinction between "normal" CLI mode, and a cron call. gahooa's command line argument idea is probably the best and most reliable solution.
但是,此处列出的这个或任何其他列出的方法都不会让您区分“正常”CLI模式和cron调用。 gahooa的命令行参数思想可能是最好和最可靠的解决方案。
#4
2
You can check the PHP_SAPI
constant to check if the CLI interpreter is being used:
您可以检查PHP_SAPI常量以检查是否正在使用CLI解释器:
$is_cli= PHP_SAPI == 'cli';
$ is_cli = PHP_SAPI =='cli';