PHP 可以检测它是从 cron 作业还是从命令行运行?
我正在寻找 PHP 的方法来检测脚本是从 shell 上的手动调用运行的(我登录并运行它),还是从 crontab 条目运行.
I'm looking for way to PHP to detect if a script was run from a manual invocation on a shell (me logging in and running it), or if it was run from the crontab entry.
我有各种用 php 编写的维护类型脚本,我已将它们设置为在我的 crontab 中运行.有时,我需要提前手动运行它们,或者如果出现故障/损坏,我需要运行几次.
I have various maintenance type scripts written in php that i have set to run in my crontab. Occasionally, and I need to run them manually ahead of schedule or if something failed/broken, i need to run them a couple times.
这样做的问题是,我在任务中也设置了一些外部通知(发布到 Twitter、发送电子邮件等),我不想在每次手动运行脚本时发生这些通知.
The problem with this is that I also have some external notifications set into the tasks (posting to twitter, sending an email, etc) that I DONT want to happen everytime I run the script manually.
我使用的是 php5(如果重要的话),它是一个相当标准的 linux 服务器环境.
I'm using php5 (if it matters), its a fairly standard linux server environment.
有什么想法吗?
推荐答案
与其检测脚本何时从 crontab 运行,不如手动运行脚本更容易检测.
Instead of detecting when the script is run from the crontab, it's probably easier to detect when you're running it manually.
当您从命令行运行脚本时,会设置很多环境变量(在 $_ENV 数组中).这些将根据您的服务器设置和登录方式而有所不同.在我的环境中,手动运行脚本时设置了以下环境变量,而从 cron 运行时不存在这些环境变量:
There are a lot of environment variables (in the $_ENV array) that are set when you run a script from the command line. What these are will vary depending on your sever setup and how you log in. In my environment, the following environment variables are set when running a script manually that aren't present when running from cron:
- 期限
- SSH_CLIENT
- SSH_TTY
- SSH_CONNECTION
还有其他的.例如,如果您始终使用 SSH 访问该框,那么以下行将检测脚本是否从 cron 运行:
There are others too. So for example if you always use SSH to access the box, then the following line would detect if the script is running from cron:
$cron = !isset($_ENV['SSH_CLIENT']);
相关文章