Checking Run Environment Dynamically with Coldfusion

Posted on Friday, October 23rd, 2009 at 6:55 am

I’ve run into a problem in the past of switching between the local development environment and the production environment for a website and always having to change my base file path in the Application.cfc file.  I always set my base file path in the Application file so that if in the future a site’s domain changes I can quickly make a global sweep on the website changing any absolute paths to whatever the new URL is.  However, during production we usually work in two environments.  One is locally, and another is under a VPS IP or dedicated server IP.  So we have two base URLs like locally – http://localhost:8500/rootDirectory, and on a VPS (or the like) – http://555.55.555.55/rootDirectory, and once this goes into production will become http://www.mySiteName.com.

The problem I’ve run into is that every time I make a change to the Application.cfc I have to change my base path to the IP to upload it to the server, and then change it back when I start working locally again.  Although this is usually a pretty quick process it can be much quicker.  Quicker as in you don’t have to change it at all.

So to the meat of this.

In the Application.cfc under the onRequestStart method add the following code:

<!--- GET THE HOST --->
<cfset VARIABLES.url = CGI.http_host>

<!--- CHECK IF 'LOCALHOST' IS PART OF THAT --->
<cfset VARIABLES.isLocal = find("localhost", VARIABLES.url)>

<cfif VARIABLES.isLocal neq 0>
	<!--- IS LOCAL --->
	<cfset APPLICATION.environment = "localhost:8500/rootDirectory">
<cfelse>
	<!--- ON SERVER --->
	<cfset APPLICATION.environment = "555.55.555.55/rootDirectory">
</cfif>

<!--- SET BASE FILE PATH --->
<cfset APPLICATION.baseFilePath = "http://" & APPLICATION.environment>

So just set this block of code to the specifics of your environment (your ip and root directory), and you should be able to move between the two environments without having to update your base file path.

One last note.  This is something that should be used only for development.  Once the site goes into production and is attached to a specific domain.  You should set in the onApplicationStart method a cfparam of something like APPLICATION.baseFilePath = “http://www.mySiteName.com”.  At this point you shouldn’t be changing the Application.cfc that often so you should remove the above code from the onRequestStart method.

CategoryColdfusion

Leave a Reply

*
(Won't be published) *