简体   繁体   English

相当于$ _SERVER ['DOCUMENT_ROOT'],当cron调用脚本时它会起作用?

[英]equivalent to $_SERVER['DOCUMENT_ROOT'] that will work when script is called by cron?

I'm using $_SERVER['DOCUMENT_ROOT'] for my include paths so files will figure out where they are running from (ie whether they're on live or staging) and it works fine, except for scripts that are run by cron in which I have to hardcode the path. 我正在使用$_SERVER['DOCUMENT_ROOT']作为我的包含路径,因此文件将确定它们的运行位置(即它们是在实时还是暂存)并且它工作正常,除了由cron运行的脚本我必须硬编码路径。

Is there another variable I could use that could work from both cron and the browser? 我可以使用另一个可以在cron和浏览器中使用的变量吗?

When running your PHP script through cron, I assume it is executed in the context of the CLI instead of the web server. 通过cron运行PHP脚本时,我认为它是在CLI的上下文而不是Web服务器上执行的。 In the case of executing PHP from the CLI, the $_SERVER['DOCUMENT_ROOT'] is not populated correctly. 在从CLI执行PHP的情况下,$ _SERVER ['DOCUMENT_ROOT']未正确填充。 You can use the following code to work around this: 您可以使用以下代码解决此问题:

if ($_SERVER['DOCUMENT_ROOT'] == "")
   $_SERVER['DOCUMENT_ROOT'] = dirname(__FILE__);

The following will give you the directory that your script is located in: 以下内容将为您提供脚本所在的目录:

realpath(dirname(__FILE__));

This works for both web requests and cron scripts. 这适用于Web请求和cron脚本。

The best thing to do is to define your own constant that you can reference from anywhere else in your app. 最好的办法是定义自己的常量,您可以从应用程序的任何其他位置引用它。 For example, you can put something like this in MyAppDirectory/public_html/index.php: 例如,您可以在MyAppDirectory / public_html / index.php中放置类似的内容:

define('APPLICATION_PATH', realpath(dirname(__FILE__).'/..'));

This will give you a consistent reference back to MyAppDirectory/ regardless of where index.php is called or included from. 无论在哪里调用或包含index.php,这都会为您提供一致的MyAppDirectory引用。 Defining your own constant not only allows you to call your application from cron or through the browser like you want, but will also allow you to change your storage structure in much larger ways with minimum changes to track down. 定义自己的常量不仅允许您从cron或通过浏览器调用您的应用程序,而且还允许您以更小的方式更改存储结构,只需最少的更改即可跟踪。 Zend Framework uses this heavily with its Zend_Application bootstrap process, and googling for "php APPLICATION_PATH" will provide you with a variety of further references. Zend Framework在Zend_Application引导过程中大量使用它,谷歌搜索“php APPLICATION_PATH”将为您提供各种进一步的参考。

You can use chdir() function, if your script is running via cron: 如果你的脚本是通过cron运行的,你可以使用chdir()函数:

chdir(dirname(__FILE__)); //avoid conflict with "cron path" and app base path (if script runs via 'Cron')

I work on Windows, so use "nnCron", but it have to work on Linux too. 我在Windows上工作,所以使用“nnCron”,但它也必须在Linux上工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM