Search code examples
phplocalhoststaging

$_SERVER['HTTP_HOST'] different on localhost versus deployment staging server


We discovered bugs in our site after deploying from our localhost development environment to our staging server. We narrowed the bugs down to the following PHP code snippet:

     $_SERVER['HTTP_HOST']

We use that to construct paths to various files used by our website.

For example:

         // EXAMPLE #1 -- THIS WORKS ON OUR LOCAL MACHINE
      $theSelectedImage = "http://" . $_SERVER['HTTP_HOST'] . "/ourWebSite/egyptVase.png";

        // EXAMPLE #2 --BUT IT MUST BE THIS TO WORK ON THE STAGING SERVER
      $theSelectedImage = "http://" . $_SERVER['HTTP_HOST'] . "/egyptVase.png";

Here is the crux of the problem:

  • on our localhost machine, $_SERVER['HTTP_HOST'] resolves to 'localhost' -- notice we then need to append our website folder name like I show in EXAMPLE #1 above. I.E. on our localhost machine, $_SERVER['HTTP_HOST'] is unaware of which website folder involved -- we have to append it.

  • but on our staging server, $_SERVER['HTTP_HOST'] resolves to 'www.ourWebSite.com'. In that case we don't need to append anything -- the staging web server returns our website folder.

Have we thought of a couple kludgy inelegant 'snide-remarks-in-code-reviews' workarounds. Yes.

But I'm thinking there's a better way -- any ideas?


Solution

  • The config file is the correct answer.. I use an default and override set up. In config.php

    $config = array('url' => 'http://production.url'); // 'conf1'=> 'var1', etc
    $dev_config = array();
    @include_once('dev-config.php');
    $config = array_merge($config, $dev_config);
    

    In dev-config.php you add any overrides to the $dev_config

    $dev_config['url'] = 'http://localhost/ourWebSite';
    

    Then in production, I just delete the dev-config file. Super easy, works flawlessly.

    If you want to keep it the way you have it, this can also be solved with an http.conf tweak on your dev box. You need to set your documentRoot to what ever it is now plus the /ourWebSite that way http://localhost/ will point to the same folder with in your code as http://production.url/