简体   繁体   中英

Including php files with sub includes in cron job and website

I have a website that uses a bunch of classes that are all saved in separate PHP files, some of these files sub-include additional class files like this:

require_once($_SERVER['DOCUMENT_ROOT'].'/../models/database.model.php');

The problem is I want to run a cron job that uses the same set of class files but when I do the path to sub-included class files breaks.

How can I specify a path for included class files so they will work for my website AND any cron jobs?

Path to cron job:

$HOME/bin/updatephotos.php

Path to classes:

$HOME/models/....

Path to public web root:

$HOME/www/...

You can solve using absolute paths

require_once(__DIR__ . '/../models/database.model.php');

The alternative is to use a little (ugly) hack: You can populate the $_SERVER['DOCUMENT_ROOT'] on your own

if (empty($_SERVER['DOCUMENT_ROOT'])) {
    $_SERVER['DOCUMENT_ROOT'] = __DIR__ . '/../www';
}

After further research I've found the following solution:

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

This works in my cron jobs plus the website.

Your include framework is using a system variable for uses for which it is not intended. It should declare its own constant which the other include files use. Then you can declare it in one, central place, ideally in the main include point of your framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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