Absolute (or relative?) Path in PHP

Sorry for the question, as it can be answered many times earlier, but my question is a little different

I have a tree like

/var/www/path/to/my/app/
   -- index.php
   -- b.php
   -- inc/
      -- include.php

(I refer to inc / include.php from index.php,

include "inc/include.php";

)

but in include.php, I need to get the absolute path to the root of APPLICATION, not DOCUMENT_ROOT so as a result I need to be able to use this command

//inc/include.php
include(APP_ROOT."/b.php");

I repeat, I DO NOT WANT TO CALL LOVE

include("../b.php");

is there a native function, if possible?

UPDATE:

I want to get PATH from PHP, since any open source must have this path detection Why? If I wanted to include inc / include.php from ajax / 1 / somethiing.php it would succeed, but inc / include.php would try to include ajax / b.php instead of b.php

For Pekka:

I have this tree

-- index.php
-- b.php
-- inc/
    -- include.php
-- ajax/
    -- 1/
       -- ajax.php

Now take a look. From index.php you will call inc / include.php

include("inc/include.php"); //included file

include("../b.php");

, ! include inc/include.php ajax/1/ajax.php,

include("../../inc/include.php");

,

../b.php 

  .. /../b.php , , inc/include.php ?

+1
6

, ?

. - , PHP. ( , include("b.php");, script index.php.)

:

. , config.php .

define("APP_ROOT", dirname(__FILE__));

, ,

include ("../../../config.php");

, script:

include (APP_ROOT."/b.php");  <--  Will always return the correct path
+5

include dirname(__FILE__) . DIRECTORY_SEPARATOR . '/../b.php';

PHP5.3

include __DIR__ . \DIRECTORY_SEPERATOR . '/../b.php';
+2

index.php:

$GLOBALS['YOUR_CODE_ROOT'] = dirname(__FILE__);

inc/include.php:

require_once $GLOBALS['YOUR_CODE_ROOT'].'/b.php';
+1

define('APP_ROOT', 'your app root');

index.php, . .

+1

If you only know the relative path, you need to at least start with the relative path. You can use realpath to return the canonical absolute path name, and then save it somewhere.

In your index.phpor config file:

define(
    'INC',
    realpath(dirname(__FILE__)) .
    DIRECTORY_SEPARATOR .
    'inc' .
    DIRECTORY_SEPARATOR
);

In the other place:

include(INC . 'include.php');

Alternatively, define several constants for different locations:

define('DOCUMENT_ROOT', realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR);
define('INC', DOCUMENT_ROOT . 'inc' . DIRECTORY_SEPARATOR);
define('AJAX', DOCUMENT_ROOT . 'ajax' . DIRECTORY_SEPARATOR);

In the other place:

include(DOCUMENT_ROOT . 'b.php');
include(INC . 'include.php');
include(AJAX . 'ajax.php');
+1
source

All Articles