这是获取服务器绝对路径的最佳方法

I have two options right now that I am working with to get absolute path of the server. My main concerns are speed and stability of the server. I am trying to find a method to replace $_SERVER['CONTEXT_DOCUMENT_ROOT'] as I am no longer using this method.

I am not only trying to find a solution to a problem, but also trying to learn in the process. I asked a previous question on StackOverflow to find out exactly how the first method was actually being processed to learn more about that (Found a PHP function for absolute path and curious exactly how it works), and now I am trying to find out if it is the best option or if there are better options.

I am open for input for even better solutions if you have any as well.

First method:

function findRoot() {
    return(substr($_SERVER["SCRIPT_FILENAME"], 0, (stripos($_SERVER["SCRIPT_FILENAME"], $_SERVER["SCRIPT_NAME"])+1));

}

Second method:

echo realpath($_SERVER["DOCUMENT_ROOT"]);

I have never used either method on a live server to test stability, so I was hoping to get some input from others. Advantages and Disadvantages would be greatly appreciated.

Really, the only best way is to just set a constant/variable at the top level and refer to that. Most larger programs do this as it is the most reliable way to find the actual document root. Usually this is set in an installer. I generally bootstrap all my apps and just set a constant there.

I generally write a new setup based on what I'm doing. I just add a .htaccess file with:

RewriteEngine On
RewriteRule (.*) index.php

in the root of my app. That will route all requests, whether the page exists or not to index.php. Then I setup a few variables, include a config file, connect to db and stuff like that. Then parse the url to figure out what page I need to include. That is pretty much it.

Also, static things like javascript, css or images, I just put into a public folder (usually in their own folder by type) and add an htaccess file with

RewriteEngine Off

So those files don't get routed through index.php. It is just overhead otherwise. You could change the rule in the first htaccess file to not include those files, but I just find it easier to use two separate.

There are a few micro-frameworks that have been suggested to me like slim that is supposed to work well for this stuff.