3

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?

Casey
  • 1,941
  • 3
  • 17
  • 30

4 Answers4

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

Marwelln
  • 28,492
  • 21
  • 93
  • 117
  • Yes this works! I'm a little confused though. I was under the impression that the ../ would move me back one dir from where I was. – Casey Oct 27 '12 at 21:27
  • I should add that it's not being included from index. – Casey Oct 27 '12 at 21:33
  • @Casey It's current directory dependent while __DIR__ is current file dependent. Current directory can change arbitrarily but current file directory... not really :) – CodeAngry Oct 27 '12 at 21:34
  • @Casey The index file was just an example. – Marwelln Oct 27 '12 at 21:49
  • Maybe this is where I'm confused. The file I'm going to in my web browser is showing a list. So in that file is something like `$list=MyFile::getlist();foreach($list as $li){echo $li;)` So is calling a static function like that similar to a include in that MyFile path is now the same as the page that is calling? – Casey Oct 27 '12 at 22:06
1

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.

Community
  • 1
  • 1
CodeAngry
  • 12,760
  • 3
  • 50
  • 57
0

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.

Ray
  • 40,256
  • 21
  • 101
  • 138
  • No it is the file being served. I'm testing it now so I'm going to it directly instead of through index for example. – Casey Oct 27 '12 at 21:26
0

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"

Chris Miller
  • 493
  • 2
  • 10
  • No it is the file being served. I'm testing it now so I'm going to it directly instead of through index for example – Casey Oct 27 '12 at 21:29