Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require PHP files relatively (at different directory levels)?

I have the following file structure:

 rootDIR     dir1         subdir1            file0.php            file1.php     dir2        file2.php        file3.php        file4.php    

file1.php requires file3.php and file4.php from dir2 like this :

require('../../dir2/file3.php') 

file2.php requires file1.php like this:

require('../dir1/subdir1/file1.php') 

But then require in file1.php fails to open file3.php and file4.php ( maybe due to the path relativeness)

However, what is the reason and what can I do for file2.php so file1.php properly require file3.php and file4.php?

like image 495
Boris D. Teoharov Avatar asked Oct 18 '12 12:10

Boris D. Teoharov


People also ask

HOW include PHP file in another directory?

The way I do it is visual. I put my mouse pointer on the index. php (looking at the file structure), then every time I go UP a folder, I type another "../" Then you have to make sure you go UP the folder structure ABOVE the folders that you want to start going DOWN into. After that, it's just normal folder hierarchy.

What is relative path in PHP?

Relative pathsIf you don't supply the root, it means that your path is relative. The simplest example of relative path is just a file name, like index. html . So one should be careful with relative paths. If your current directory is /about/ then index.

How do you create a relative path?

Relative path Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.


2 Answers

For relative paths you can use __DIR__ directly rather than dirname(__FILE__) (as long as you are using PHP 5.3.0 and above):

require(__DIR__.'/../../dir2/file3.php'); 

Remember to add the additional forward slash at the beginning of the path within quotes.

See:

  • PHP - with require_once/include/require, the path is relative to what?
  • PHP - Relative paths "require"
like image 55
SharpC Avatar answered Oct 15 '22 10:10

SharpC


Try adding dirname(__FILE__) before the path, like:

require(dirname(__FILE__).'/../../dir2/file3.php'); 

It should include the file starting from the root directory

like image 26
Baronth Avatar answered Oct 15 '22 11:10

Baronth