如何区分命令行和Web服务器调用

如何区分命令行和Web服务器调用

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

问题描述

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

(参见以获得最佳答案和更详细的讨论-在发布前未找到该方法) >


我有一个(非生产性的)服务器,安装了Apache 2.2.10和PHP 5.2.6.在它的Web访问目录中,是我的PHP脚本maintenance_tasks.php.我想从命令行或通过HTTP请求(通过在浏览器中打开)调用此脚本.是否有一些变量可以让我可靠地确定脚本的调用方式?

(我已经解决了每种调用类型和HTTP响应超时的不同视图问题,只是在寻找一种将两种调用类型区分开的方法)

我将尝试不同的方法,并在下面添加我的发现.

重复:

解决方案

更新:由于此答案仍被标记为正确",因此我想修改我的声明-依靠"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?

解决方案

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服务器调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 12:00