哪种方法检测php脚本的运行模式更可靠?
我现在了解如何检测天气 php 脚本在 cli 或 web 服务器模式下运行:
if (defined('STDIN'))
或者:
if (isset($argc))
它们是否同样可靠或其中之一更可靠?
I now to ways to detect weather php script runs in cli or web server mode:
if (defined('STDIN'))
or:
if (isset($argc))
Do they equally reliable or one of them is more ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两者都不。检查
php_sapi_name()
返回的值。Neither. Check the value returned from
php_sapi_name()
.由于缺少 HTTP 请求,因此不会设置 $_SERVER['REQUEST_METHOD']。不过,我认为 Defined( 'STDIN' ) 或 isset( $argc ) 也可靠。如果由我决定,我可能会使用定义的('STDIN'),因为我可以想象有人不小心将值设置为 $argc。
上面的 php_sapi_name 函数似乎是确定这一点的另一种(最可靠的?)方法,尽管我确实认为阅读所有陷阱是个好主意:请注意不同的服务器会给出不同的答案。
$_SERVER['REQUEST_METHOD'] won't be set, due to the lack of a HTTP request. I think defined( 'STDIN' ) or isset( $argc ) are reliable too, though. If it was up to me, I'd probably go with the defined( 'STDIN' ), as I can imagine someone accidentally setting a value to $argc.
The php_sapi_name function above seems to be another (the most reliable?) way of determining this, although I do think it'd be a good idea to read all the gotcha's: mind that different servers will give different answers.