How to Include PHP Files That Require an Absolute Path

How to include PHP files that require an absolute path?

This should work

$root = realpath($_SERVER["DOCUMENT_ROOT"]);

include "$root/inc/include1.php";

Edit: added imporvement by aussieviking

PHP include absolute path

You can't include php files relatively to your webroot that way, cause if you use the slash as first character, the reference will go much deeper than just your document root. So, instead of using your basepath, you could do something like this :

<?php 
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/yourpath/yourfile.php";
include_once($path);
?>

Can't include or require an absolute path

Paths you give to include or require are paths on the local filesystem. They are not what you see in URLs to access your site. An absolute path starting with / is from the root of the filesystem. In Windows terms, /foo is C:\foo\. Relative paths like foo/bar are relative to the the PATH configuration variable, which depends on how your PATH is set up which also includes which PHP file was invoked.

It's typically not a good idea to use absolute paths, since those are likely different on different systems (as you are experiencing). On your local machine the site may live in C:\core\..., but on the server it'll be running in /var/www/mysite/core/.... PATHs can also be cumbersome to work with. The best is typically to use __DIR__ or __FILE__ magic constants to construct an absolute path relative to the current file (if that made sense):

require __DIR__ . '/some/folder/file.php`;

This includes the file some/folder/file.php relative to the file in which it is written.

Setting the path for include / require files

Don't

I would advise against using anything that needs something outside of PHP, like the $_SERVER variable.

$_SERVER['DOCUMENT_ROOT'] is usually set by the webserver, which makes it unusable for scripts running from the command line. So don't use this.

Also don't use url's. The path-part in a url is not the same as the path of the file on disk. In fact, that path can not even exist on disk (think Apache rewrites).

Including url's also needs you to turn allow_url_include on, which introduces (severe) security risks if used improperly.

Do

If your minimal supported PHP version is 5.3 (I hope it is!), you can use the magic constant __DIR__. 2 examples:

define(ROOT_DIR, __DIR__);
define(ROOT_DIR, realpath(__DIR__ . '/..'));

If you need to support lower versions, use dirname(__FILE__). 2 examples:

define(ROOT_DIR, dirname(__FILE__));
define(ROOT_DIR, realpath(dirname(__FILE__) . '/..'));

Make sure ROOT_DIR points to the root of you project, not some subdirectory inside it.

You can then safely use ROOT_DIR to include other files:

include ROOT_DIR . '/some/other/file.php';

Note that I'm defining a constant (ROOT_DIR), not a variable. Variables can change, but the root directory of you project doesn't, so a constant fits better.

realpath()

realpath() will resolve any relative parts and symlinks to the canonicalized absolute pathname.

So given the following files and symlink:

/path/to/some/file.php
/path/to/another/file.php
/path/to/symlink => /path/to/another

and /path/to/file.php contains:

define(ROOT_DIR, realpath(__DIR__ . '/../symlink'));

then ROOT_DIR would become /path/to/another, because:

  • __DIR__ equals to /path/to/some (so we get /path/to/some/../symlink)
  • .. is 1 directory up (so we get /path/to/symlink)
  • symlink points to /path/to/another

You don't really need to use realpath(), but it does tidy up the path if you're relying on relative parts or symlinks. It's also easier to debug.

Autoloading

If you need to include files that contain classes, you'd best use autoloading. That way you won't need include statements at all.

Use a framework

One last pease of advise: This problem has been solved many many times over. I suggest you go look into a framework like Symfony, Zend Framework, Laravel, etc. If you don't want a "full stack" solution, look into micro-frameworks like Silex, Slim, Lumen, etc.

Including files in PHP scripts from any directory with absolute path

did you try autoloading? http://php.net/manual/en/language.oop5.autoload.php .. Sorry I dont have permissions to write comments yet..

Updated.. Wesley is right, you will need to have the class name same as file name for autoload to work. I am sorry to assume that you are doing OOP-PHP. If not autoload will not work you will have to do it traditional way

function __autoload($class) {
require ABSPATH. $class .".php";
}

Any file inside the ABSPATH with classname = filename will be automatically loaded.

If you have various paths with different files in them than you will have to create multiple constant variables with path name. And than call them inside autoload with the specific path.

for eg.

class Myprogram{

public function __construct(){

define('ABSPATH', '/home/dalyn/public_html/');
define('ABSPATH_1', '/home/dalyn/public_html/includes');
define('ABSPATH_2', '/home/dalyn/public_html/some_other_folder');

}

function __autoload($class) {
require ABSPATH. $class .".php";
require ABSPATH_1. $class .".php";
require ABSPATH_2. $class .".php";
}

}

//Some other file
$myProg = new Myprogram(); // this will define your constants as well as autoload all the required files

and if you are not using OOP. Than you will have to define different paths as constants and include the files the way you do it now.
and if you want to automate this process

this code will be helpful.

if ($handle = opendir(ABSPATH)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
include_once ABSPATH . $entry;
}
}
closedir($handle);
}

this will include all the files present in the folder ABSPATH. You can create a function and call it with whatever path you want to put.

Hope this helps.

Dins

How do I format a PHP include() absolute (rather than relative) path?

If you give include() or require() (or the *_once versions) an absolute pathname, that file will be included. An absolute pathname starts with a "/" on unix, and with a drive letter and colon on Windows.

If you give a relative path (any other path), PHP will search the directories in the configuration value "include_path" in order, until a match is found or there are no more directories to search.

So, in short, to include an absolute filename, give an absolute filename. See also the function realpath().

If you want to set your own include "root", have a look at this question (specifically my answer of course :-)

How do I set an absolute include path in PHP?

What I do is put a config.php file in my root directory. This file is included by all PHP files in my project. In that config.php file, I then do the following;

define( 'ROOT_DIR', dirname(__FILE__) );

Then in all files, I know what the root of my project is and can do stuff like this

require_once( ROOT_DIR.'/include/functions.php' );

Sorry, no bonus points for getting outside of the public directory ;) This also has the unfortunate side affect that you still need a relative path for finding config.php, but it makes the rest of your includes much easier.

PHP require_once Absolute Path vs Relative Path (Not Working)

../ denotes the parent directory, compared to the one you're currently in. Therefore, your first line says "go one directory up and look for config/constants.php in there". What you'd want to use with a relative path here is ./ (note the single dot), which denotes your current directory.

This has little to do with programming in specific, it's more of a file-system thing.

You can use this as a reference:

  • leading / (no dots, just a slash) means an absolute path
  • leading ./ (single dot) means the current directory
  • leading ../ (two dots) means one directory up
  • no leading dots or slashes is the same thing as with the single dot - relative to the current directory.

Update (to account for edited question):

What has something to do with programming and PHP in particular is that what is considered the "current" directory is usually the one where you initially executed the script from.
Under a CLI environment, that may vary, but if you're accessing the script via the web that is the location of the PHP file which you have directly accessed. E.g. if you're pointing your browser to example.com/test.php, then wherever 'test.php' is located is the directory you're currently in.

That can be changed by chdir() of course.



Related Topics



Leave a reply



Submit