For people like me who came from C++ or other languages that take a rational approach to "include" and "require" statements, I thought I’d put up this tip about a generic way to use php includes in MODx that will work on both your localhost and a remote site without editing.
In MODx, the current working directory is usually the base directory (where index.php lives). Complicating this, is the fact the php, unlike C+++, uses the cwd of the including file rather than the included file. As a result, it’s hard sometimes to know how to include a file in a nested include, especially if the included file is in another directory.
It’s easy to get confused about $modx->config[’base_path’] and all its relatives and I often have things break when I move from localhost (Windows/Xampp) to a remote site (*nix).
This will generally work to include a file on any server if you know the relative path from the file you’re currently in to the file you want to include or require:
$path = realpath(dirname(__FILE__)."/relative/path/to/included/file.inc.php");
include $path;
If the file to include is in the same directory as the file you’re editing, it’s just:
$path = realpath(dirname(__FILE__)."/file.inc.php");
include $path;
If you like tighter code, you can use:
include realpath(dirname(__FILE__)."/file.inc.php");
I often separate them at first in case I want to echo $path to see if it looks right.
Note that there are
two underscore characters before and after "FILE."
If you’re still having trouble after doing this, look for a www translation where yoursite.com gets converted to www.yoursite.com (or vice versa) either in .htaccess or by your hosting service.
Hope this saves people some of the trouble I went through to discover it.
Bob