PHP: how to not tightly manage the root web application

My application currently has the following:

define('DOCROOT', dirname(__FILE__).DIRECTORY_SEPARATOR); define('WEBROOT', 'http://localhost/samples/'); 

The first line works fine. I can include the configuration file anywhere, and then use the DOCROOT constant as expected.

The second line also works, but it is hard-coded, which means that when this file is uploaded to my web server, it will be incorrect. There should be http://samples.example.com . Is there a good way to somehow prevent this hard coding? I kind of think that I need to hard code something, and in this case, what and how little can I avoid?

+7
source share
5 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']), '/\\') . '/' ; } 
+3
source
 define('WEBROOT', 'http://'.$_SERVER['HTTP_HOST'].'/'); 
+2
source

You can go one step further and make sure the user accesses 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); 
+1
source

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

0
source
 '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 configuration file.

0
source

All Articles