Reputation: 20765
how can i get the root to the main folder? for example i run file in this location :
public_html/admin/user/etc/index.php
and i want to include file from
public_html/includes/user/etc/function.php
so i want to do something like this:
include(get_first_default_folder().'includes/user/etc/function.php');
instead of:
include('../../../includes/user/etc/function.php');
Upvotes: 3
Views: 10745
Reputation: 2167
This a bit clumsy approach I guess but it works for me. On the beginning of every file I define a variable $root
. First level variable is $root = './'
(this is not required thought), first subfolder is $root = '../'
, second subfolder is $root = '../../'
and so forth. $root
always takes me to the root folder of my site.
When I need to provide a path I just do something like include("{$root}includes/user/etc/function.php");
This helped me to get rid of "no such index or file" warnings so I'll stick with it until I find a better way of doing the same thing.
Alternatively you could define a constant for each folder level so you don't have to add $root
at the top of the every file. (Haven't tested it so I don't know if the following syntax is correct.) Instead you'd do something like:
After defining the constants somewhere:
Upvotes: 1
Reputation: 35149
I normally do this thusly. $myDir = dirname(__FILE__);
(or you can use __DIR__
on PHP v5.3+) is the directory name that the particular file is in. You know where in the hierarchy this is, so you can easily get the base with $myBaseDir = realpath('../../../'.$mydir)
'. Realpath expands the path to it's canonical version, not including any symbolic links. Having the full path can also allows for a small speedup when it comes to including or otherwise finding files.
The reason I do that, rather than using $_SERVER['DOCUMENT_ROOT']
, is that that environment variable probably won't exist if I'm running a script from the command line - it's set by the webserver.
Upvotes: 2
Reputation: 597
You can use Document root from $_SERVER['DOCUMENT_ROOT'].
You can include this line in your index.php file.
include("{$_SERVER['DOCUMENT_ROOT']}includes/user/etc/function.php");
Upvotes: 4