I can't believe PHP doesn't have an easy solution of this simple matter. ASP.NET has a ~ sign that cares of this issue and starts everything from 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 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" of 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.
You can access the $_SERVER['DOCUMENT_ROOT'] variable :
Create a constant with absolute path to the root by using
define
inShowInfo.php
:Or PHP <= 5.3
Now use it:
Or use the
DOCUMENT_ROOT
defined in$_SERVER
:The best way Using dirname(). Because SERVER['DOCUMENT_ROOT'] not working all servers, and also return server running path.
In PHP there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the 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.
use
dirname(__FILE__)
in a global configuration file.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 :
The path
LOCAL_PATH_ROOT
is the document root. The pathHTTP_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 :
If you want to ensure compatibility with Windows based servers, you'll need to replace the directory seperator with a URL seperator as well :
Here's the full bootstrap code that I'm using for the PHP PowerTools boilerplate :
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 :