如何区分命令行和Web服务器调用? [英] How to distinguish command-line and web-server invocation?

查看:127
本文介绍了如何区分命令行和Web服务器调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以区分是从命令行还是由Web服务器调用了脚本?

(参见确定PHP脚本的命令行执行与HTTP执行的规范方法是什么?

解决方案

如果从命令行调用,则不会设置服务器变量HTTP_USER_AGENT.我使用此常量来定义是否从命令行调用脚本:

define("CLI", !isset($_SERVER['HTTP_USER_AGENT']));

更新:由于此答案仍被标记为正确",因此我想修改我的声明-依靠"User-Agent"标头可能会出现问题,因为这是一个用户定义的值.

请使用Eugene/cam8001在评论中建议的php_sapi_name() == 'cli'PHP_SAPI == 'cli'.

感谢您指出这一点!

Is there a way to distinguish if a script was invoked from the command line or by the web server?

(See What is the canonical way to determine commandline vs. http execution of a PHP script? for best answer and more detailed discussion - didn't find that one before posting)


I have a (non-production) server with Apache 2.2.10 and PHP 5.2.6. On it, in a web-accessible directory is my PHP script, maintenance_tasks.php. I would like to invoke this script from the command line or through a HTTP request (by opening in a browser). Is there some variable that allows me to reliably determine how script is invoked?

(I already tackled the issues of different views for each type of invocation and HTTP response timeout, just looking for a way of telling the two invocation types apart)

I'll be trying different things and add my findings below.

Duplicate: What is the canonical way to determine commandline vs. http execution of a PHP script?

解决方案

If called from command line, the server variable HTTP_USER_AGENT is not set. I use this constant to define, whether the script is called from command line or not:

define("CLI", !isset($_SERVER['HTTP_USER_AGENT']));

UPDATE: Since this answer is still marked as the 'correct' one, I'd like to revise my statement - relying on the "User-Agent" header can be problematic, since it's a user-defined value.

Please use php_sapi_name() == 'cli' or PHP_SAPI == 'cli', as suggested by Eugene/cam8001 in the comments.

Thanks for pointing this out!

这篇关于如何区分命令行和Web服务器调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆