Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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://localhost/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?

like image 842
Svish Avatar asked Jul 04 '11 17:07

Svish


1 Answers

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']), '/\\')
         . '/'
    ;
}
like image 100
NikiC Avatar answered Oct 03 '22 10:10

NikiC