How to Require PHP Files Relatively (At Different Directory Levels)

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

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"

relative path in require_once doesn't work

Use

__DIR__

to get the current path of the script and this should fix your problem.

So:

require_once(__DIR__.'/../class/user.php');

This will prevent cases where you can run a PHP script from a different folder and therefore the relatives paths will not work.

Edit: slash problem fixed

How to use a PHP includes across multiple directories/sub directories with relative paths

i usualy have a file called config in my application root and in it i define a constant for base path and a few others:

define('APP_BASE_PATH', dirname(__FILE__));
define('APP_FUNCTIONS_PATH', APP_BASE_PATH . '/functions');

and i include my files like

include (APP_BASE_PATH . 'includes/another_file.php');
include (APP_FUNCTIONS_PATH . '/function_file.php');

that way i can place my aplication in whatever directory, plus i can move files around without to much worries.

also using full path makes the include faster

Include php files when they are in different folders

You can get to the root from within each site using $_SERVER['DOCUMENT_ROOT']. For testing ONLY you can echo out the path to make sure it's working, if you do it the right way. You NEVER want to show the local server paths for things like includes and requires.

Site 1

echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/';

Includes under site one would be at:

echo $_SERVER['DOCUMENT_ROOT'].'/includes/'; // should be '/main_web_folder/includes/';

Site 2

echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/blog/';

The actual code to access includes from site1 inside of site2 you would say:

include($_SERVER['DOCUMENT_ROOT'].'/../includes/file_from_site_1.php');

It will only use the relative path of the file executing the query if you try to access it by excluding the document root and the root slash:

 //(not as fool-proof or non-platform specific)
include('../includes/file_from_site_1.php');

Included paths have no place in code on the front end (live) of the site anywhere, and should be secured and used in production environments only.

Additionally for URLs on the site itself you can make them relative to the domain. Browsers will automatically fill in the rest because they know which page they are looking at. So instead of:

<a href='http://www.__domain__name__here__.com/contact/'>Contact</a>

You should use:

<a href='/contact/'>Contact</a>

For good SEO you'll want to make sure that the URLs for the blog do not exist in the other domain, otherwise it may be marked as a duplicate site. With that being said you might also want to add a line to your robots.txt file for ONLY site1:

User-agent: *
Disallow: /blog/

Other possibilities:

Look up your IP address and include this snippet of code:

function is_dev(){
//use the external IP from Google.
//If you're hosting locally it's 127.0.01 unless you've changed it.
$ip_address='xxx.xxx.xxx.xxx';

if ($_SERVER['REMOTE_ADDR']==$ip_address){
return true;
} else {
return false;
}
}

if(is_dev()){
echo $_SERVER['DOCUMENT_ROOT'];
}

Remember if your ISP changes your IP, as in you have a DCHP Dynamic IP, you'll need to change the IP in that file to see the results. I would put that file in an include, then require it on pages for debugging.

If you're okay with modern methods like using the browser console log you could do this instead and view it in the browser's debugging interface:

if(is_dev()){
echo "<script>".PHP_EOL;
echo "console.log('".$_SERVER['DOCUMENT_ROOT']."');".PHP_EOL;
echo "</script>".PHP_EOL;
}

PHP require file from top directory

There are several ways to achieve this.

Use relative path from form.php

require_once __DIR__ . '/otherfile.php';

If you're using PHP 5.2 or older, you can use dirname(__FILE__) instead of __DIR__. Read more about magic constants here.

Use the $_SERVER['DOCUMENT_ROOT'] variable

This is the absolute path to your document root: /var/www/example.org/ or C:\wamp\www\ on Windows.

The document root is the folder where your root level files are: http://example.org/index.php would be in $_SERVER['DOCUMENT_ROOT'] . '/index.php'

Usage: require_once $_SERVER['DOCUMENT_ROOT'] . '/include/otherfile.php';

Use an autoloader

This will probably be a bit overkill for your application if it's very simple.

Set up PHP's include paths

You can also set the directories where PHP will look for the files when you use require() or include(). Check out set_include_path() here.

Usage: require_once 'otherfile.php';


Note:

I see some answers suggest using the URL inside a require(). I would not suggest this as the PHP file would be parsed before it's included. This is okay for HTML files or PHP scripts which output HTML, but if you only have a class definition there, you would get a blank result.

making relative path for include files

I always included a config.php in the first line of each php:

require_once($_SERVER['DOCUMENT_ROOT']."/".(explode ('/', $_SERVER['PHP_SELF'])[1])."/config.php");

This code should always find the root directory, and then include the config.php file.
Note that you can put this file anywhere you want - it will always find it's location on its own. If you move the file to another directory subsequently, you don't have to change anything.

This config file then defines the paths to all subdirectories and other important files, relative to the root directory:

$paths = array(
"root" => "",
"controller" => "controller",
"stylesheets" => "css",
"images" => array(
"icons" => "img/icons",
"controls" => "img/controls"
),
"javascript" => array(...),
...
);

This array means, that the root folder (your public_html) contains the directories "controller", "stylesheets", images" and so on. Images are either placed within "img/icons" or "img/controls".

All other files are included so:

require_once($paths['helper']['html']."/form.php");

This can be very useful, because it allows you to restructure your complete directory layout, and you only need to update your config.php.

And, last but not least, the config also contains a function like this:

$projectName = "YourProjectFolderName";
function fInc($filePath){
global $projectName;
return '//'.$_SERVER['HTTP_HOST'].'/'.$projectName.'/'.$filePath;
}

It can be used to convert paths which will be inserted into the HTML document.

Edit:
Note, that defining an array with all paths is just a suggestion. It helped me in my projects, as I often restructure my project layout. If you don't do that in your project, you can just define a

$rootDir = $_SERVER['DOCUMENT_ROOT']."/".(explode ('/', $_SERVER['PHP_SELF'])[1]);

and then include files with

require_once($rootDir . "/home/index.php");

This way, you won't need the config.php anymore.

PHP - Relative paths require

If you find that relative include paths aren't working as expected, a quick fix is to prepend __DIR__ to the front of the path you're trying to include.

require __DIR__ . "/../blog.php";

It's reasonably clean, and you don't need to modify the include path or working directory.



Related Topics



Leave a reply



Submit