Search code examples
phprelative-pathrequire-once

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?


Solution

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