简体   繁体   中英

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?

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';

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.

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM