1

I have a php file which has a require_once Statement (?) this file is then in included in 2 other php files, one php file is in a sub directory so the layout is like this ("file1" and "file2" include the file "included" which require_onces the "required")#

 L--subfolder1
 | L--file1
 L--subfolder2
 | L--required
 L--file2
 L--included

How can I reference the "required" file from the "included" file so that it will work from both file1 and file2?

Jonathan.
  • 53,997
  • 54
  • 186
  • 290

3 Answers3

5

always use absolute path

$_SERVER['DOCUMENT_ROOT']."/included";

or

$_SERVER['DOCUMENT_ROOT']."/subfolder2/required";

would work from anywhere

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • Thank you for the quick and correct answer I thought it would be a Server variable but wasn't sure which one even after looking in the php docs. – Jonathan. Apr 16 '10 at 11:27
  • 2
    NOTE: that $_SERVER['DOCUMENT_ROOT'] does not work in CRON only in a web browser – Phill Pafford Apr 16 '10 at 12:55
4

You have to use absolute path to be able to require the file with the same code from anywhere.

require_once($_SERVER['DOCUMENT_ROOT'] . '/subfolder2/required');
Petr Peller
  • 8,581
  • 10
  • 49
  • 66
4

You can use dirname() in combination with the __FILE__ constant. (If I understand you correctly you're including the file 'included' from both scripts and 'included' then includes some files?)
included(.php):

require_once( dirname(__FILE__)."/subfolder2/required" );
svens
  • 11,438
  • 6
  • 36
  • 55
  • 1
    Quick heads-up, dirname() returns the directory without a trailing slash, so you'll want to have that be `require_once( dirname(__FILE__)."/subfolder2/required" );` - note extra slash. – pinkgothic Apr 16 '10 at 11:25