Casey
Casey

Reputation: 1981

include, require and relative paths

I'm not sure why I always have some many problems with this. Anyways this is the path to the file I want to require

/var/www/vhosts/mysite.com/htdocs/Classes/DBConnection.php

This is the path to the file that has the require statement

/var/www/vhosts/mysite.com/htdocs/Classes/Forecast/MyFile.php

and this is the require statement in MyFile.php

require_once '../DBConnection.php';

I keep getting the "failed to open stream" error. It works fine if I put in an absolute path. Does anyone see the problem here?

Upvotes: 3

Views: 301

Answers (4)

CodeAngry
CodeAngry

Reputation: 12985

I have a detailed answer on this in another question:

finding a file in php that is 4 directories up

It explains the caveats of relative file paths in PHP. Use the magic constants and server variables mentioned there to overcome relative path issues.

Upvotes: 1

Chris Miller
Chris Miller

Reputation: 493

Make your path relative to the initially requested file. So if you're hitting /var/www/vhosts/mysite.com/htdocs/index.php, which includes MyFile.php, your path would be "Classes/DBConnection.php"

Upvotes: 0

Ray
Ray

Reputation: 41428

Yep. The path is relative to the file your including your class file MyFe.php from and not the class file itself. I am assuming MyFile.php is not really the page being served, but an included or autoloaded class.

Upvotes: 0

Marwelln
Marwelln

Reputation: 29413

If /Classes/Forecast/MyFile.php is included from /index.php the relative path will be from the index file. To solve this, use __DIR__. The require will then be relative from that file.

require_once __DIR__.'/../DBConnection.php';

Upvotes: 1

Related Questions