[php] PHP absolute path to root

I can't believe PHP doesn't have an easy solution for this simple matter. ASP.NET has a ~ sign that takes care of this issue and starts everything from the root level. Here's my problem:

localhost/MySite
   -->Admin
      -- Edit.php
   -->Class
      -- class.EditInfo.php
   -->Texts
      -- MyInfo.txt
   --ShowInfo.php

Inside class.EditInfo.php I am accessing MyInfo.txt so I defined a relative path "../Texts/MyInfo.txt". Then I created an object of EditInfo in Admin/Edit.php and accessed Texts/MyInfo.txt - it worked fine.

But now I have to create an object of EditInfo in ShowInfo.php and access Texts/MyInfo.txt and here's the problem that occurs. As I am using a relative path in my class, whenever I am creating an objEditInfo and trying to access MyInfo.txt I am getting "File doesn't exist" error.

Now I am looking for something that's equivalent to "~/Texts/MyInfo.txt" from ASP.NET. Is there anything similar to that out there??? Or do I have to set the path with some if/else condition?


UPDATE:

I used $_SERVER['DOCUMENT_ROOT']. I was using a subfolder where my actual website was. So I had to use $_SERVER['DOCUMENT_ROOT']."/mySite" & then adding rest of the address ("/Texts/MyInfo.php") to it.

This question is related to php relative-path absolute-path

The answer is


It always best to start any custom PHP project with a bootstrap file where you define the most commonly used paths as constants, based on values extracted from $_SERVER. It should make migrating your projects or parts of your project to another server or to another directory on the server a hell of a lot easier.

This is how I define my root paths :

define("LOCAL_PATH_ROOT", $_SERVER["DOCUMENT_ROOT"]);
define("HTTP_PATH_ROOT", isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : (isset($_SERVER["SERVER_NAME"]) ? $_SERVER["SERVER_NAME"] : '_UNKNOWN_'));

The path LOCAL_PATH_ROOT is the document root. The path HTTP_PATH_ROOT is the equivalent when accessing the same path via HTTP.

At that point, converting any local path to an HTTP path can be done with the following code :

str_replace(LOCAL_PATH_ROOT, RELATIVE_PATH_ROOT, $my_path)

If you want to ensure compatibility with Windows based servers, you'll need to replace the directory seperator with a URL seperator as well :

str_replace(LOCAL_PATH_ROOT, RELATIVE_PATH_ROOT, str_replace(DIRECTORY_SEPARATOR, '/', $my_path))

Here's the full bootstrap code that I'm using for the PHP PowerTools boilerplate :

defined('LOCAL_PATH_BOOTSTRAP') || define("LOCAL_PATH_BOOTSTRAP", __DIR__);

// -----------------------------------------------------------------------
// DEFINE SEPERATOR ALIASES
// -----------------------------------------------------------------------
define("URL_SEPARATOR", '/');
define("DS", DIRECTORY_SEPARATOR);
define("PS", PATH_SEPARATOR);
define("US", URL_SEPARATOR);

// -----------------------------------------------------------------------
// DEFINE ROOT PATHS
// -----------------------------------------------------------------------
define("RELATIVE_PATH_ROOT", '');
define("LOCAL_PATH_ROOT", $_SERVER["DOCUMENT_ROOT"]);
define("HTTP_PATH_ROOT",
        isset($_SERVER["HTTP_HOST"]) ?
        $_SERVER["HTTP_HOST"] : (
        isset($_SERVER["SERVER_NAME"]) ?
        $_SERVER["SERVER_NAME"] : '_UNKNOWN_'));

// -----------------------------------------------------------------------
// DEFINE RELATIVE PATHS
// -----------------------------------------------------------------------
define("RELATIVE_PATH_BASE",
        str_replace(LOCAL_PATH_ROOT, RELATIVE_PATH_ROOT, getcwd()));
define("RELATIVE_PATH_APP", dirname(RELATIVE_PATH_BASE));
define("RELATIVE_PATH_LIBRARY", RELATIVE_PATH_APP . DS . 'vendor');
define("RELATIVE_PATH_HELPERS", RELATIVE_PATH_BASE);
define("RELATIVE_PATH_TEMPLATE", RELATIVE_PATH_BASE . DS . 'templates');
define("RELATIVE_PATH_CONFIG", RELATIVE_PATH_BASE . DS . 'config');
define("RELATIVE_PATH_PAGES", RELATIVE_PATH_BASE . DS . 'pages');
define("RELATIVE_PATH_ASSET", RELATIVE_PATH_BASE . DS . 'assets');
define("RELATIVE_PATH_ASSET_IMG", RELATIVE_PATH_ASSET . DS . 'img');
define("RELATIVE_PATH_ASSET_CSS", RELATIVE_PATH_ASSET . DS . 'css');
define("RELATIVE_PATH_ASSET_JS", RELATIVE_PATH_ASSET . DS . 'js');

// -----------------------------------------------------------------------
// DEFINE LOCAL PATHS
// -----------------------------------------------------------------------
define("LOCAL_PATH_BASE", LOCAL_PATH_ROOT . RELATIVE_PATH_BASE);
define("LOCAL_PATH_APP", LOCAL_PATH_ROOT . RELATIVE_PATH_APP);
define("LOCAL_PATH_LIBRARY", LOCAL_PATH_ROOT . RELATIVE_PATH_LIBRARY);
define("LOCAL_PATH_HELPERS", LOCAL_PATH_ROOT . RELATIVE_PATH_HELPERS);
define("LOCAL_PATH_TEMPLATE", LOCAL_PATH_ROOT . RELATIVE_PATH_TEMPLATE);
define("LOCAL_PATH_CONFIG", LOCAL_PATH_ROOT . RELATIVE_PATH_CONFIG);
define("LOCAL_PATH_PAGES", LOCAL_PATH_ROOT . RELATIVE_PATH_PAGES);
define("LOCAL_PATH_ASSET", LOCAL_PATH_ROOT . RELATIVE_PATH_ASSET);
define("LOCAL_PATH_ASSET_IMG", LOCAL_PATH_ROOT . RELATIVE_PATH_ASSET_IMG);
define("LOCAL_PATH_ASSET_CSS", LOCAL_PATH_ROOT . RELATIVE_PATH_ASSET_CSS);
define("LOCAL_PATH_ASSET_JS", LOCAL_PATH_ROOT . RELATIVE_PATH_ASSET_JS);

// -----------------------------------------------------------------------
// DEFINE URL PATHS
// -----------------------------------------------------------------------
if (US === DS) { // needed for compatibility with windows
    define("HTTP_PATH_BASE", HTTP_PATH_ROOT . RELATIVE_PATH_BASE);
    define("HTTP_PATH_APP", HTTP_PATH_ROOT . RELATIVE_PATH_APP);
    define("HTTP_PATH_LIBRARY", false);
    define("HTTP_PATH_HELPERS", false);
    define("HTTP_PATH_TEMPLATE", false);
    define("HTTP_PATH_CONFIG", false);
    define("HTTP_PATH_PAGES", false);
    define("HTTP_PATH_ASSET", HTTP_PATH_ROOT . RELATIVE_PATH_ASSET);
    define("HTTP_PATH_ASSET_IMG", HTTP_PATH_ROOT . RELATIVE_PATH_ASSET_IMG);
    define("HTTP_PATH_ASSET_CSS", HTTP_PATH_ROOT . RELATIVE_PATH_ASSET_CSS);
    define("HTTP_PATH_ASSET_JS", HTTP_PATH_ROOT . RELATIVE_PATH_ASSET_JS);
} else {
    define("HTTP_PATH_BASE", HTTP_PATH_ROOT .
            str_replace(DS, US, RELATIVE_PATH_BASE));
    define("HTTP_PATH_APP", HTTP_PATH_ROOT .
            str_replace(DS, US, RELATIVE_PATH_APP));
    define("HTTP_PATH_LIBRARY", false);
    define("HTTP_PATH_HELPERS", false);
    define("HTTP_PATH_TEMPLATE", false);
    define("HTTP_PATH_CONFIG", false);
    define("HTTP_PATH_PAGES", false);
    define("HTTP_PATH_ASSET", HTTP_PATH_ROOT .
            str_replace(DS, US, RELATIVE_PATH_ASSET));
    define("HTTP_PATH_ASSET_IMG", HTTP_PATH_ROOT .
            str_replace(DS, US, RELATIVE_PATH_ASSET_IMG));
    define("HTTP_PATH_ASSET_CSS", HTTP_PATH_ROOT .
            str_replace(DS, US, RELATIVE_PATH_ASSET_CSS));
    define("HTTP_PATH_ASSET_JS", HTTP_PATH_ROOT .
            str_replace(DS, US, RELATIVE_PATH_ASSET_JS));
}

// -----------------------------------------------------------------------
// DEFINE REQUEST PARAMETERS
// -----------------------------------------------------------------------
define("REQUEST_QUERY",
        isset($_SERVER["QUERY_STRING"]) && $_SERVER["QUERY_STRING"] != '' ?
        $_SERVER["QUERY_STRING"] : false);
define("REQUEST_METHOD",
        isset($_SERVER["REQUEST_METHOD"]) ?
        strtoupper($_SERVER["REQUEST_METHOD"]) : false);
define("REQUEST_STATUS",
        isset($_SERVER["REDIRECT_STATUS"]) ?
        $_SERVER["REDIRECT_STATUS"] : false);
define("REQUEST_PROTOCOL",
        isset($_SERVER["HTTP_ORIGIN"]) ?
        substr($_SERVER["HTTP_ORIGIN"], 0,
        strpos($_SERVER["HTTP_ORIGIN"], '://') + 3) : 'http://');
define("REQUEST_PATH",
        isset($_SERVER["REQUEST_URI"]) ?
        str_replace(RELATIVE_PATH_BASE, '',
        $_SERVER["REQUEST_URI"]) : '_UNKNOWN_');
define("REQUEST_PATH_STRIP_QUERY",
        REQUEST_QUERY ?
        str_replace('?' . REQUEST_QUERY, '', REQUEST_PATH) : REQUEST_PATH);

// -----------------------------------------------------------------------
// DEFINE SITE PARAMETERS
// -----------------------------------------------------------------------
define("PRODUCTION", false);
define("PAGE_PATH_DEFAULT", US . 'index');
define("PAGE_PATH",
        (REQUEST_PATH_STRIP_QUERY === US) ?
        PAGE_PATH_DEFAULT : REQUEST_PATH_STRIP_QUERY);

If you add the above code to your own project, outputting all user constants at this point (which you can do with get_defined_constants(true) should give a result that looks somewhat like this :

array (
  'LOCAL_PATH_BOOTSTRAP' => '/var/www/libraries/backend/Data/examples',
  'URL_SEPARATOR' => '/',
  'DS' => '/',
  'PS' => ':',
  'US' => '/',
  'RELATIVE_PATH_ROOT' => '',
  'LOCAL_PATH_ROOT' => '/var/www',
  'HTTP_PATH_ROOT' => 'localhost:8888',
  'RELATIVE_PATH_BASE' => '/libraries/backend/Data/examples',
  'RELATIVE_PATH_APP' => '/libraries/backend/Data',
  'RELATIVE_PATH_LIBRARY' => '/libraries/backend/Data/vendor',
  'RELATIVE_PATH_HELPERS' => '/libraries/backend/Data/examples',
  'RELATIVE_PATH_TEMPLATE' => '/libraries/backend/Data/examples/templates',
  'RELATIVE_PATH_CONFIG' => '/libraries/backend/Data/examples/config',
  'RELATIVE_PATH_PAGES' => '/libraries/backend/Data/examples/pages',
  'RELATIVE_PATH_ASSET' => '/libraries/backend/Data/examples/assets',
  'RELATIVE_PATH_ASSET_IMG' => '/libraries/backend/Data/examples/assets/img',
  'RELATIVE_PATH_ASSET_CSS' => '/libraries/backend/Data/examples/assets/css',
  'RELATIVE_PATH_ASSET_JS' => '/libraries/backend/Data/examples/assets/js',
  'LOCAL_PATH_BASE' => '/var/www/libraries/backend/Data/examples',
  'LOCAL_PATH_APP' => '/var/www/libraries/backend/Data',
  'LOCAL_PATH_LIBRARY' => '/var/www/libraries/backend/Data/vendor',
  'LOCAL_PATH_HELPERS' => '/var/www/libraries/backend/Data/examples',
  'LOCAL_PATH_TEMPLATE' => '/var/www/libraries/backend/Data/examples/templates',
  'LOCAL_PATH_CONFIG' => '/var/www/libraries/backend/Data/examples/config',
  'LOCAL_PATH_PAGES' => '/var/www/libraries/backend/Data/examples/pages',
  'LOCAL_PATH_ASSET' => '/var/www/libraries/backend/Data/examples/assets',
  'LOCAL_PATH_ASSET_IMG' => '/var/www/libraries/backend/Data/examples/assets/img',
  'LOCAL_PATH_ASSET_CSS' => '/var/www/libraries/backend/Data/examples/assets/css',
  'LOCAL_PATH_ASSET_JS' => '/var/www/libraries/backend/Data/examples/assets/js',
  'HTTP_PATH_BASE' => 'localhost:8888/libraries/backend/Data/examples',
  'HTTP_PATH_APP' => 'localhost:8888/libraries/backend/Data',
  'HTTP_PATH_LIBRARY' => false,
  'HTTP_PATH_HELPERS' => false,
  'HTTP_PATH_TEMPLATE' => false,
  'HTTP_PATH_CONFIG' => false,
  'HTTP_PATH_PAGES' => false,
  'HTTP_PATH_ASSET' => 'localhost:8888/libraries/backend/Data/examples/assets',
  'HTTP_PATH_ASSET_IMG' => 'localhost:8888/libraries/backend/Data/examples/assets/img',
  'HTTP_PATH_ASSET_CSS' => 'localhost:8888/libraries/backend/Data/examples/assets/css',
  'HTTP_PATH_ASSET_JS' => 'localhost:8888/libraries/backend/Data/examples/assets/js',
  'REQUEST_QUERY' => false,
  'REQUEST_METHOD' => 'GET',
  'REQUEST_STATUS' => false,
  'REQUEST_PROTOCOL' => 'http://',
  'REQUEST_PATH' => '/',
  'REQUEST_PATH_STRIP_QUERY' => '/',
  'PRODUCTION' => false,
  'PAGE_PATH_DEFAULT' => '/index',
  'PAGE_PATH' => '/index',
)

The best way to do this given your setup is to define a constant describing the root path of your site. You can create a file config.php at the root of your application:

<?php

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

$file_path = SITE_ROOT . '/Texts/MyInfo.txt';

?>

Then include config.php in each entry point script and reference SITE_ROOT in your code rather than giving a relative path.


use dirname(__FILE__) in a global configuration file.


In PHP there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:

 $_SERVER['DOCUMENT_ROOT']

The only problem is that the entries in this variable are provided by the web server and there is no guarantee that all web servers offer them.


You can access the $_SERVER['DOCUMENT_ROOT'] variable :

<?php 
   $path = $_SERVER['DOCUMENT_ROOT'];
   $path .= "/subdir1/yourdocument.txt";
?>

The best way Using dirname(). Because SERVER['DOCUMENT_ROOT'] not working all servers, and also return server running path.

$root = dirname( __FILE__ );

$root = __DIR__;

$filePath = realpath(dirname(__FILE__));

$rootPath = realpath($_SERVER['DOCUMENT_ROOT']);

$htmlPath = str_replace($root, '', $filePath);

This is my way to find the rootstart. Create at ROOT start a file with name mainpath.php

<?php 
## DEFINE ROOTPATH
$check_data_exist = ""; 

$i_surf = 0;

// looking for mainpath.php at the aktiv folder or higher folder

while (!file_exists($check_data_exist."mainpath.php")) {
  $check_data_exist .= "../"; 
  $i_surf++;
  // max 7 folder deep
  if ($i_surf == 7) { 
   return false;
  }
}

define("MAINPATH", ($check_data_exist ? $check_data_exist : "")); 
?>

For me is that the best and easiest way to find them. ^^


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to relative-path

webpack: Module not found: Error: Can't resolve (with relative path) Reading file using relative path in python project How to import a CSS file in a React Component How to open my files in data_folder with pandas using relative path? Relative path in HTML Failed to load resource: the server responded with a status of 404 (Not Found) How does Java resolve a relative path in new File()? relative path in BAT script How to define a relative path in java Relative imports for the billionth time

Examples related to absolute-path

Server Document Root Path in PHP Do I need to pass the full path of a file in another directory to open()? PHP absolute path to root How to use relative/absolute paths in css URLs? src absolute path problem Relative path to absolute path in C#? Get filename and path from URI from mediastore Convert absolute path into relative path given a current directory using Bash How to get the file-path of the currently executing javascript code Resolve absolute path from relative path and/or file name