The better way to handle session variables

As web applications grow, the number of variables used for various purposes also increases. When you use the session scope for these variables, they can eventually begin filling up the server's memory and slow down your site.

One easy way to keep your server (and site) running fast is by deleting variables from memory after they are no longer needed. You could do this manually for each variable, but by using a simple naming convention for separate areas of your site, you can easily manipulate all variables for that area at any time by looping over the session structure.

For example, let's say you have two sections of your site: Application and Enrollment.

When you create your session variables for each section, prefix the variable names with a description of the section they are for.

i.e. For the Application section, prefix your variables with 'app_' and use 'enroll_' for the 
Enrollment section. This example uses the Application ('app_') section as an example.


<cflock timeout="10" throwontimeout="No" type="EXCLUSIVE" scope="SESSION"
   
<!--- your variables will be set at different times throughout the site this is just an example... --->
    <cfset session.app_1 =
"1">
    ...
    <cfset session.app_100 = "100">
</cflock>


If you want to convert all your session variables to the request scope, run this script.

<cflock timeout="30" throwontimeout="No" type="READONLY" scope="SESSION">
    <CFLOOP collection=
"#Session#" item="var">
        <!--- the 'if' statement is the key to how this works - the variable prefix of 'app_' allows
                you to loop through all session variables but only convert the ones you want.
         --->

        <cfif var contains "app_">
            <cfset setvariable(
"request." & var, session[var])>
        </cfif>
    </CFLOOP> 
</cflock>


If you want to delete the variables from memory at some point, run this script.

<cflock timeout="10" throwontimeout="No" type="EXCLUSIVE" scope="SESSION"
    <cfloop collection=
"#Session#" item="var">
        <cfif var contains
"app_">
            <cfset structdelete(session,var)>
        </cfif>
    </cfloop>
</cflock>


This method preserves any important variables that you want to maintain, while easily manipulating or deleting others.



All ColdFusion Tutorials By Author: Nathan Miller