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.


Solution 1:

Create a constant with absolute path to the root by using define in ShowInfo.php:

define('ROOTPATH', __DIR__);

Or PHP <= 5.3

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

Now use it:

if (file_exists(ROOTPATH.'/Texts/MyInfo.txt')) {
  // ...
}

Or use the DOCUMENT_ROOT defined in $_SERVER:

if (file_exists($_SERVER['DOCUMENT_ROOT'].'/Texts/MyInfo.txt')) {
  // ...
}

Solution 2:

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.