Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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 which I have to hardcode the path.

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

like image 283
sbuck Avatar asked Feb 19 '10 19:02

sbuck


3 Answers

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__);
like image 182
Rouan van Dalen Avatar answered Nov 19 '22 01:11

Rouan van Dalen


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.

like image 28
zombat Avatar answered Nov 19 '22 01:11

zombat


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.

like image 41
Kevin Vaughan Avatar answered Nov 19 '22 01:11

Kevin Vaughan