检测 Cron 作业是否正在临时服务器上运行
我正在构建一个网站,该网站每天都会运行一系列 cron 任务来更新数据库中的信息,然后在该网站中使用这些信息。我设置了三个环境:开发(我的计算机)、登台和实时。登台和现场都是共享托管上的帐户。我遇到的问题是根据代码运行的环境来决定使用哪个数据库访问凭据。理想情况下,所有三个都具有相同的凭据,但由于登台和实时都在共享服务器上,我无法控制数据库的名称。我已在自己的计算机上镜像实时数据库名称和访问凭据,但无法在暂存时执行此操作。
我想要做的是,当我的 cron 任务运行时,自动为正确的环境选择正确的凭据,如下所示:
if(environment === staging) {
//define db access constants for staging here
else {
//define db access constants for live or dev here
}}
通常对于此类事情,我会使用 $_SERVER['SERVER_NAME'] 但因为这是在 Cron 中运行$_SERVER 自动全局不可用。如何检测 cron 作业中脚本正在哪个环境中运行?
I'm building a website that will run a series of cron tasks daily to update information in a database that is then used in the site. I have three environments setup: development (my computer), staging and live. Both staging and live are accounts on shared hosting. The problem I have is in deciding which database access credentials to use depending on which environment the code is running on. Ideally all three would have the same credentials but as both staging and live are on a shared server I can't control the name of the database. I've mirrored the live database name and access credentials on my own computer but I can't do this on staging.
What I want to do is to automatically select the correct credentials for the correct environment when my cron task runs, something like this:
if(environment === staging) {
//define db access constants for staging here
else {
//define db access constants for live or dev here
}}
Normally for this sort of thing I'd use $_SERVER['SERVER_NAME'] but as this is running in Cron the $_SERVER auto global isn't available. How could I detect on which environment a script is running in a cron job?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在 crontab 文件中添加一个额外的环境变量:
然后检查
$_ENV['STAGING'] == 1
。或者甚至
然后检查
$_ENV['HOSTING_ENV'] == 'Production'
。You could put an extra environment variable in the crontab file:
and then check for
$_ENV['STAGING'] == 1
.Or even
and then check for
$_ENV['HOSTING_ENV'] == 'PRODUCTION'
.ajreal和gms8994这两个环境变量解决方案都不错。另一种方法是使用 php_uname() 获取当前主机名:
The environment variable solutions that ajreal and gms8994 are both good. Another method is to use php_uname() to fetch the current hostname:
通过 WGET 运行您的 cron,通过域而不是 PHP 命令行调用它,
然后您将能够通过其域检测平台
run your cron via WGET by calling it by a domain rather by PHP command line
you will then be able to detect the platform by its domain