I cant for the life of me get PHP’s ‘include’ statement to work on any files other than files in the same directory as the file using the ‘include’ statement. When I try to include any file from another directory the whole app breaks and nothing loads.
I dump that script in, say:
/var/www/html/fooA/testClass.php
and try to include it using:
/var/www/html/different_than_fooA/include_testClass.php
and the app breaks. However, if I include:
/html/foo_1.php
in:
/html/foo_2.php
everything works fine…
I promise this is not a simple syntax issue, I’ve tried writing it every way possible, using slashes in front, or no slash in front, whole directories and partial directories, IP addresses, even tried loading from other servers. My guess is it has to do with the way PHP or Apache is configured. Almost nothing hits on this matter that I can find floating around the internet, any advice would be great.
<?php
// THIS FILE IS TEST/TEST02.php
require 'TEST01.php';
$V = new X();
$V->Z();
?>
2
Answers
You can always use PHP’s magic constants and that way you can be sure that it will figure out the correct path for you.
Here is the link to documentation. https://www.php.net/manual/en/language.constants.predefined.php
By default PHP sets the
include_path
as follows:On *nix systems
On Widows systems
You can, and should, override these defaults to suit your environment as it is unlikely that you will have placed all the relevant files in these locations.
In order to override the default locations use
set_include_path("/path/to/includes/")
etc which then allows a simple call to include the files like this:If you need to load class files one alternative would be to use the
__autoload
method equivalent and write your own callback to handle loading of files. The original__autoload
method is deprecated but an improvedspl_autoload
class exists to facillitate this.The following references
ALIASED_SITE_ROOT
andROOT_PATH
which are globally defined constants on my system and point to particular directories so will not be relevant to you and will need editing if you decide to adopt this approach to loading classes.More info on “spl_autoload_register”
With the above registered in a common include file when you need to load a class you no longer need to do
require '/path/to/includes/foobar.php';
when you need to work with the file you could simply do:So the above works well with classes – a consistent naming strategy will help immensely if you adopt this approach! For example, I tend to locate all classes in what is shown above as
ALIASED_SITE_ROOT . '/inc/'
and use a naming convention ofclass.foobar.php
so in the autoload functionis actually
It follows that the class name must match the name given by
$classname
, for example: