PHP可以检测它是否从cron作业或从命令行运行? [英] Can PHP detect if its run from a cron job or from the command line?

查看:115
本文介绍了PHP可以检测它是否从cron作业或从命令行运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找PHP的方法来检测脚本是否从手动调用运行shell(我登录并运行它),或者如果它是从crontab条目运行。



我有各种维护类型的脚本用php编写,我已经设置运行在我的crontab。偶尔,我需要提前手动运行它们,或者如果失败/损坏,我需要运行它们几次。



这个问题是,我还有一些外部通知设置到任务(发布到微博,发送电子邮件等),我DONT想要发生每当我手动运行脚本。



任何想法?



< >解决方案

不是检测脚本是否从crontab运行,而是手动运行脚本可能更容易检测。



当从命令行运行脚本时,有很多环境变量(在$ _ENV数组中)被设置。这些都取决于您的服务器设置和登录方式。在我的环境中,当运行脚本时,如果从cron运行时不存在以下环境变量:




  • TERM

  • SSH_CLIENT

  • SSH_TTY

  • SSH_CONNECTION



还有其他的。例如,如果你总是使用SSH访问框,然后下面的行将检测脚本是否从cron运行:



$ cron =!isset($ _ ENV ['SSH_CLIENT']);


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.

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.

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.

I'm using php5 (if it matters), its a fairly standard linux server environment.

Any ideas?

解决方案

Instead of detecting when the script is run from the crontab, it's probably easier to detect when you're running it manually.

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:

  • TERM
  • SSH_CLIENT
  • SSH_TTY
  • SSH_CONNECTION

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']);

这篇关于PHP可以检测它是否从cron作业或从命令行运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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