How can a PHP script detect if it has been invoked as a script or from the shell?

≯℡__Kan透↙ 提交于 2019-12-24 16:31:50

问题


I have a PHP script on a webserver.

This file is invoked via the shell by another program but it could still be run by the webserver in response to an HTTP request.

How can the script determine the way it was invoked?


回答1:


There are lots of ways; I check if $_SERVER['HTTP_HOST'] is empty. I think the technically correct way is to see if php_sapi_name() returns cli




回答2:


If it is executed from the shell then it won't have HTTP headers because it wasn't requested from HTTP protocols.




回答3:


There are certain environmental variables you can check. for example $_SERVER["REQUEST_METHOD"]

if (isset($_SERVER["REQUEST_METHOD"]))
   // run by server

good luck




回答4:


I write a lot of applications that run concurrently in the shell and web contexts, and this one liner makes it easy

function isWEB()
         {
         return $GLOBALS['argc']===NULL;
         }


来源:https://stackoverflow.com/questions/2671649/how-can-a-php-script-detect-if-it-has-been-invoked-as-a-script-or-from-the-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!