PHP Require File from Top Directory

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.

Include files from parent or other directory

include() and its relatives take filesystem paths, not web paths relative to the document root. To get the parent directory, use ../

include('../somefilein_parent.php');
include('../../somefile_2levels_up.php');

If you begin with a /, an absolute system file path will be used:

// Full absolute path...
include('/home/username/sites/project/include/config.php');

PHP require a file from another directory: No such file or directory

Try absolute path instead relative path. Change the following

require '../Models/Database.php';

to

require $_SERVER['DOCUMENT_ROOT'].'/Models/Database.php';

'DOCUMENT_ROOT'
The document root directory under which the current script is executing, as defined in the server's configuration file.
http://php.net/manual/en/reserved.variables.server.php

Change of folder path when require/ include an php file

Make sure you always include with an absolute path, like:

require_once(dirname(__FILE__) . "/otherfile.php");
require_once(dirname(__FILE__) . "/../uponefolder.php");
require_once(dirname(__FILE__) . "/sub/folder/file.php");

Or use autoloading.

PHP Require In different folders

A good practice is to include a main config in all running php files, usually called config.php :)

in this config file create a constant called SITE_ROOT or something similar that point to the exact folder like this
define("SITE_ROOT", "/var/www/mysite");

Then on any include, include_once, require, require_once use it like this:

require(SITE_ROOT."/scripts/connect.php");

This should solve any relative path drama

Include files from parent or other directory

include() and its relatives take filesystem paths, not web paths relative to the document root. To get the parent directory, use ../

include('../somefilein_parent.php');
include('../../somefile_2levels_up.php');

If you begin with a /, an absolute system file path will be used:

// Full absolute path...
include('/home/username/sites/project/include/config.php');

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.

PHP how to go one level up on dirname(__FILE__)

For PHP < 5.3 use:

$upOne = realpath(dirname(__FILE__) . '/..');

In PHP 5.3 to 5.6 use:

$upOne = realpath(__DIR__ . '/..');

In PHP >= 7.0 use:

$upOne = dirname(__DIR__, 1);

How to include() PHP file with just a directory path like this folder_1 not folder_1/index.php?

There is no concept of "default file to include" in PHP. However, you can easily create a helper function to accomplish this. (Whether this makes sense or not, I leave for you to decide.)

function import(string $dir) {
include $dir . 'index.php';
}

Note that if your file to import contains variables, they will be "lost" in the function's scope. If your file only defines classes, functions, constants etc. that are scope-independent, this will work fine. (Refer to my original answer for importing variables from files using a helper function.)


Edit: It turns out OP wasn't asking about including multiple files. My original answer has been ported over to: How to include() all PHP files from a directory?.



Related Topics



Leave a reply



Submit