PHP 脚本如何检测它是作为脚本调用还是从 shell 调用?

发布于 2024-08-29 10:48:10 字数 120 浏览 3 评论 0原文

我在网络服务器上有一个 PHP 脚本。

该文件由另一个程序通过 shell 调用它仍然可以由网络服务器运行以响应 HTTP 请求。

脚本如何确定它的调用方式?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

起风了 2024-09-05 10:48:17

方法有很多;我检查 $_SERVER['HTTP_HOST'] 是否为空。我认为技术上正确的方法是查看 php_sapi_name() 是否返回 cli

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

风追烟花雨 2024-09-05 10:48:17

如果它是从 shell 执行的,那么它不会有 HTTP 标头,因为它不是从 HTTP 协议请求的。

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

天生の放荡 2024-09-05 10:48:17

您可以检查某些环境变量。例如 $_SERVER["REQUEST_METHOD"]

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

祝你好运

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

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

good luck

日暮斜阳 2024-09-05 10:48:17

我编写了很多在 shell 和 Web 上下文中同时运行的应用程序,
这个衬垫让一切变得简单

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

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;
         }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文