So I am trying to include some files in PHP and it’s not working.
The file I am writing is in the home directory. There is a subdirectory “D1” in the home directory, and in D1, there is another directory, “D2”.
Inside D2 there are a bunch of files. I wrote a class file and stored it in D1. It looks like this:
<?php
include_once('D2/file1.php');
include_once('D2/file2.php');
//ect
class myClass {
//class stuff
}
?>
So then I write a file inside the home directory like this:
<?php
include_once('D1/myclass.php');
?>
But when I load this file, I get this:
Warning: include_once(file1.php) [function.include-once]: failed to open stream: No such file or directory in /home/D1/D2/file1.php on line 2
“file1.php” is definitely in that directory, so what am I doing wrong?
when including a file, the relative location is relative to the script being called which is the “current working directory”. so if script
A.phpincludes./test/B.phpandB.phpwanted to include a file under./test/, it would be relative toA.php. You can create an absolute path using__DIR__which has the script path and name regardless of where it was included or by using$_SERVER['DOCUMENT_ROOT']which will point to the document root.B.php example:
the other option is to add D1 to the includes path in php.ini. this tells php to look in that directory for the file when doing an include.