开发者

Referring to the public root in PHP - best practices

I've been using the $_SERVER["DOCUMENT_ROOT"] environment variable to refer to the public root in my apps. Now I'm realizing that that's not very reliable. I'm thinking about an approac开发者_JAVA百科h where I define a constant in my index.php based on a magic constant. Something like that:

define("PUBILC", __DIR__."/");

I'm not sure about it though.

What approach would you recommend?


If everything request goes through your index.php, defining a constant there would be a fine, and often used, idea. I've also seen setups defining an environmental variable with (virtual)host configuration or .htaccess, but I think its less transparent and less portable. Hardcoding paths in a settings variable is often used but less 'altering automatically' then one would hope. All in all I agree with your idea.


Definitely don't have $_SERVER['DOCUMENT_ROOT'] scattered throughout your application. Apache can be configured to use VirtualDocumentRoot which will set the document root to that directory but that will not change the DOCUMENT_ROOT environment variable which can lead to broken sites.

In line with your approach, I like to define DOC_ROOT at the top of my app and use that anywhere I need to refer to the document root.


In one os my projects I have made a config with the following lines (and some additional ones):

// set the root directory for the files
define('ROOT_DIR', "/path/to/my/htdocs/project_name/");
// set the root path for URLs
define('ROOT_PATH', "http://".$_SERVER['HTTP_HOST']."/project_name/");

Within every php file I then include this config.php using this line:

require_once($_SERVER['DOCUMENT_ROOT'].'/config_project_name.php');

As you can see using a prefix for the config files, you can put them all into your root directory and you are still flexible enough to have the same project on different PCs or servers.


You could do something similar, but put it in some common include file that gets included in all your pages. That works for visitors that come directly to a page on your site without going through the main index page.

For example, if you've got utilities.php in your doc_root/inc folder, and it gets included in all your site pages, it might look something like this:

<?php
function GetDocumentRoot()
{
    return dirname(dirname(__FILE__));
}

function WriteHeader()
{
    //...
}

// more utility functions...
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜