开发者

PHP: How not to hard code web application root

I currently have the following in a config file in my application:

define('DOCROOT', dirname(__FILE__).DIRECTORY_SEPARATOR);
define('WEBROOT', 'http://localh开发者_如何转开发ost/samples/');

The first line works perfectly. I can include the config file anywhere and then use the DOCROOT constant as expected.

The second line works as well, but it's hardcoded, which means that when I upload this file to my webserver, it will be wrong. There it should be http://samples.example.com. Is there a good way to somehow prevent this hard coding? I kind of think that I have to hard code something somewhere, and in that case, what and how little can I get away with?


I use the following code to find the base URL:

function getBaseURL() {
    return 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://'
         . $_SERVER['HTTP_HOST']
         . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\')
         . '/'
    ;
}


define('WEBROOT', 'http://'.$_SERVER['HTTP_HOST'].'/');


You can go one step further, and ensure if the user is accessing via HTTPS, you give them HTTPS....

    if (isset($_SERVER["HTTPS"]) && $_SERVER['HTTPS'] == 'on') {
            $target_url = "https://" . $_SERVER["SERVER_NAME"];
    } else {
            $target_url = "http://" . $_SERVER["SERVER_NAME"];
    }
   define('WEBROOT', $target_url);


One way to "hack" this is to check for the external requesting IP. If the ip is 127.0.0.1 define WEBROOT as http://localhost/samples, otherwise define it as http://samples.example.com


'http://'.$_SERVER['HTTP_HOST']. str_replace(str_replace("\\","/",str_replace(realpath(dirname(__FILE__)).DIRECTORY_SEPARATOR, "", realpath($_SERVER['SCRIPT_FILENAME']))), "", $_SERVER['PHP_SELF']);

I tested it on localhost. Put it in your config file.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜