问题
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?
回答1:
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';
回答2:
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.
回答3:
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.
回答4:
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"
来源:https://stackoverflow.com/questions/13104277/include-require-and-relative-paths