2

I have the following file structure:

cron.php /includes/functions.php /classes/ClassName.php

corn.php includes functions.php calls new ClassName(). And functions.php contains the primitive autoloader:

 function __autoload($class_name) {
   require_once('classes/'.$class_name.'.php');
 }

which works fine when cron.php is called from browser. However if run from shell it is giving "No such file or directory" fatal error. I tried to wrap 'classes/'.$class_name.'.php' into realpath() function to no avail. Please advise.

user487772
  • 8,800
  • 5
  • 47
  • 72

4 Answers4

4

You may use dirname(__FILE__) to get the "absolute" current directory of your autoloading PHP script.

You could do something like (supposing your autoloading script is in a subdirectory of your project):

function __autoload($class_name) {
  require_once(dirname(__FILE__).'/../classes/'.$class_name.'.php');
}

See:

Maxime Pacary
  • 22,336
  • 11
  • 85
  • 113
2
 function __autoload($class_name) {
   require_once(dirname(__file__) . '/classes/'.$class_name.'.php');
 }
Codler
  • 10,951
  • 6
  • 52
  • 65
  • It works but with small fix: `dirname(__file__) . '/../classes/'.$class_name.'.php'` as your code was including "includes" folder into path. Anyways thank you. – user487772 Apr 14 '11 at 10:49
0

how did you schedule the job? if the file is /path/to/cron.php, try something like: "cd /path/to && php cron.php", you probably do something like "php /path/to/cron.php" now, and $PWD is not /path/to/ there so classes is not found

tvlooy
  • 1,036
  • 10
  • 16
0

Because you are using relative path, and PHP directory it is in is different when invoke from browser and from CLI.

Use this function to change the directory to match the browser directory.

UPDATE: Suggest code from suggestion.

chdir(dirname(__FILENAME__));
lxcid
  • 1,023
  • 1
  • 11
  • 18
  • 2
    not a viable solution, what if you move the script around you'll allso need to edit it to corect the path . `dirname(__FILE__)` is a way better solution ! – Poelinca Dorin Apr 14 '11 at 10:50
  • I just learn about `dirname(__FILENAME__);`. so another solution is to do this `chdir(dirname(__FILENAME__));` Thanks for the pointer. :) – lxcid Apr 14 '11 at 10:52