Quickly Determine Local or Remote Copy of Your Website (with PHP)

I do a lot of web development locally on my computer and I am always switching between local and remote servers using entries in the hosts file.  Because of this, it is hard to know if I’m actually looking at the correct version of my site.  Opera and Firefox both cache DNS to various degrees which makes it difficult to know if that change to the hosts file really did take effect.  I know you can disable the cache in Firefox — and probably Opera too — but I think this method is still useful.

By using PHP’s auto_prepend_file and auto_append_file php.ini options you can easily setup a way of notifying you when you’re looking at your localhost.

First, I changed the two php.ini values above to look like:

auto_prepend_file = [path to]/auto-buffer.php
auto_append_file = [path to]/auto-buffer-end.php

auto-buffer.php source

<?php
function _auto_buffer_cb($buf, $bits) {
   if($bits | PHP_OUTPUT_HANDLER_END) {
      if(false !== stripos($buf, '</body>')) {
         return $buf.'<br /><br /><span style="background:black; color:white; border:2px solid white;">localhost</span>';
      }
   }

   return $buf;
}

// the "1" lets PHP know to only cache 4096 bytes before sending it to the browser
ob_start('_auto_buffer_cb', 1);
?>

auto-buffer-end.php source

<?php
ob_end_flush();
?>

After changing php.ini you must restart Apache for the changes to take.

Since you can nest ob_start calls, this code will not interfere with your code at all. It will also (try to) check to verify that the data PHP is returning is actually a web page, and not something like an image or serialized ajax data.

This method leaves a lot of room for improvement but it works for me, and that was what I was looking for!

Leave a Reply

© 2009 Cory Mawhorter