我有一个共同的脚本,我包括在我的 PHPcron 文件和文件正在通过浏览器访问。代码的一部分,我只需要非 cron 文件。如何检测执行是来自 CLI 还是通过浏览器(我知道可以通过使用 cron 文件传递一些参数来完成,但是我没有访问 crontab 的权限)。还有别的办法吗?
I think you can see it from the $_SERVER variables. Try to print out the $_SERVER array for both browser & CLI and you should see differences.
There is a constant PHP_SAPI has the same value as php_sapi_name().
PHP_SAPI
php_sapi_name()
(available in PHP >= 4.2.0)
You can use:
if (isset($argc)) { // CLI } else { // NOT CLI }
Use the php_sapi_name() function.
if (php_sapi_name() == "cli") { // In cli-mode } else { // Not in cli-mode }
Here are some relevant notes from the docs:
php_sapi_name — Returns the type of interface between web server and PHP Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.
php_sapi_name — Returns the type of interface between web server and PHP
Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.
if(php_sapi_name() == "cli") { //In cli-mode } else { //Not in cli-mode }