Question

I was wondering if there is a way of making a relative path to the main folder (where the index.php lies) from every file that needs to be included or requested by AJAX.

I want to combine both AJAX and PHP include so first time the page loads with PHP, and then to be able to refresh parts of the page with AJAX, but the files are the same and lie in subfolders.

I'm having problems with the path and although I can set an absolute path, then I have to change it every time the server changes. I want a relative path to where my project is, but not DOCUMENT_ROOT, because that one doesn't work with aliases. (or do you know how to make it work with aliases? )

Thanks !

EDIT* Here is how my directory structure looks:

[main_dir]/index.php - the main index file

[main_dir]/phpinc - the php include files - that work only with include (no AJAX call on them)

[main_dir]/modules - the modules are parts of the page , can be either included with PHP or AJAX called from anywhere (doesn't matter, they will be loaded as an individual HTML file, so the paths in PHP are relative to where the module is phisically situated.

When you include them in PHP, they will normally take the [main_dir] path (because index.php has included them)

So my problem is: from the module files I want to include some files in the phpinc folder, but it could either be ../phpinc/file.php or phpinc/file.php .

Is there a more elegant way than just putting an

if (is_dir("phpinc")) {
 $inc_path = "phpinc";   
} else if (is_dir("../phpinc")) {
 $inc_path = "../phpinc";
}

at the beginning of each module?
Hope this clarification is good enough.

Was it helpful?

Solution

I'd propose to use PHP's autoloader:

I created a class CAutoloadManager which has this method:

static public addRepositoryForFilePattern( String $aPath, String $sPattern ) {}

Within index.php I call

AutoloadManager::addRepositoryForFilePattern( './actions/', 'C*Action.inc.php' );
AutoloadManager::addRepositoryForFilePattern( './includes/', '*.inc.php' );

to instruct the autoload to first try to locate a Class in ./actions/ for names like CShowWelcomeAction.inc.php or CLoginAction.inc.php. The CAutoloadManager searched ./includes/ for other classes.

PHP's autoload() function is used like this:

function __autoload($class_name) {

    include $class_name . '.php';

}

PHP calls it each time it fails to load a class.

Actuall, this works very nice - although for classes only.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top