PHP - 通过 cron 作业自动检测主目录
我有一个 php 脚本并使用 Cpanel 界面创建一个 cron 作业,每 5 分钟运行一次该 php 脚本。我目前的问题是,我必须在脚本顶部的 php 脚本中手动设置根目录的路径,如下所示:
$root = '/var/home/www/site/';
然后,我使用 $root 作为路径引用任何包含/脚本。问题是我有一个开发盒,用于测试脚本,然后将其上传到主服务器。每次我都必须记住用主服务器上的正确根路径手动更改 $root 变量。有没有办法自动执行此操作,这样我就不必手动更新脚本?我尝试查看是否可以使用 $_SERVER['REMOTE_ADDR'] 获取 IP 地址,但该值为空,并且 $_SERVER['DOCUMENT_ROOT'] 值显示为 /
I have a php script and using Cpanel interface Im creating a cron job that runs this php script every 5 minutes. The question I have is currently I have to manually set the path to the root directory in my php script at the top of the script like so:
$root = '/var/home/www/site/';
Then I reference any includes/scripts using $root as the path. The problem is I have a dev box I use to test the script, then upload it to the main server. Every time I have to remember to manually change out the $root variable with the correct root path on the main server. Is there a way to do this automatically so I dont have to manually update the scripts? I tried seeing if I can get the ip address using $_SERVER['REMOTE_ADDR'] but the value is blank and the $_SERVER['DOCUMENT_ROOT'] value comes up as /
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为您正在寻找
getcwd()
。它返回当前工作目录。I think you're looking for
getcwd()
. It returns the current working directory.您可以在 crontab 文件中定义环境变量。在 crontab 的开头添加:
现在在 PHP 脚本中,您可以通过查看以下内容来掌握这一点:
知道您可以在两个实时/开发服务器上定义相同的变量,或者您可以让脚本使用以下命令查找环境变量如果存在则返回默认值,如果不存在则返回默认值。
You can define environment vars in a crontab file. At the start of the crontab add:
Now in the PHP script you can get hold of this by looking at:
Knowing that you can either define the same variable on both live/dev servers or you could have the script look for the environment variable using it if it's there or falling back to a default if it's not there.
如果它是一个 cron 作业,我猜最安全的方法是使用
dirname ( __FILE__ )
(或者,就像 James 和 Alix 所说,对于 php >= 5.3__DIR__
code>) - 它返回正在运行的脚本所在的目录。If it is a cron job, I would guess that the safest way would be to use
dirname ( __FILE__ )
(or, like James and Alix said, for php >= 5.3__DIR__
) - it returns you the directory the script being run resides in.您可以使用以下变量之一在环境之间切换:
我不确定这些是否在 CRON / php-cli 下定义,但另一种方法可能是检查文件夹是否存在:
You can probably use either one of these variables to switch between environments:
I'm not sure if these are defined under CRON / php-cli, but an alternative approach might be to check if the folder exists: