PHP 脚本如何检测它是作为脚本调用还是从 shell 调用?
我在网络服务器上有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
方法有很多;我检查
$_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 ifphp_sapi_name()
returnscli
如果它是从 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.
您可以检查某些环境变量。例如 $_SERVER["REQUEST_METHOD"]
祝你好运
There are certain environmental variables you can check. for example $_SERVER["REQUEST_METHOD"]
good luck
我编写了很多在 shell 和 Web 上下文中同时运行的应用程序,
这个衬垫让一切变得简单
I write a lot of applications that run concurrently in the shell and web contexts,
and this one liner makes it easy