TheEnigmaMachine
TheEnigmaMachine

Reputation: 613

Cannot locate file after including it in PHP

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?

Upvotes: 2

Views: 340

Answers (3)

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15311

when including a file, the relative location is relative to the script being called which is the "current working directory". so if script A.php includes ./test/B.php and B.php wanted to include a file under ./test/, it would be relative to A.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:

<?php
include(__DIR__.'/C.php');
//will include C.php under the same directory as B.php
?>

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.

Upvotes: 2

Jakub
Jakub

Reputation: 20475

If you are on a linux OS or MAC os you need to be aware of the case for your files, are the D2's capitalized or lower case? etc;

Also I noticed your class myClass { line, does that mean THIS file is being included / used by another file? In which case your relative location of the include file may change.

Upvotes: 1

Jonathan M
Jonathan M

Reputation: 17451

I'm going to guess you have a permissions problem. Check that the folders/files have the correct permissions to allow access by the web service.

Upvotes: 0

Related Questions