PHP require file from top directory PHP require file from top directory php php

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.


If one level higher use:

include('../header.php');

if two levels higher:

include('../../header.php');

Fore more, visit: http://forums.htmlhelp.com/index.php?showtopic=2922


  • suppose you have pgm1.php inwww.domain.com/dir1/dir2/dir3/pgm1.php, which include or require'dirA/inc/Xpto.php'.
  • and another pgm2.php in www.domain.com/dirZ1/dirZ2/pgm2.php, which include or require same 'dirA/inc/Xpto.php'.
  • and your Host configuration not authorize require/include'http://www.domain.com/......'
  • So...you can use this, in both pgm1.php & pgm1.php, and REQUIRE or
    INCLUDE works !

    function rURI($p){   for($w='',$i=1;$i<(count(explode('/',$_SERVER['PHP_SELF']))-1);$i++,$w.='../');return   $w.$p; }

    require rURI('dirA/inc/Xpto.php'); // path from root