开发者

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 (i.e. whether they're on live or staging) and it works fine, except for scripts that are run by cron in wh开发者_Python百科ich I have to hardcode the path.

Is there another variable I could use that could work from both cron and the browser?


When running your PHP script through cron, I assume it is executed in the context of the CLI instead of the web server. In the case of executing PHP from the CLI, the $_SERVER['DOCUMENT_ROOT'] is not populated correctly. 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.


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:

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. 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. 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.


You can use chdir() function, if your script is running via cron:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜