dcolumbus
dcolumbus

Reputation: 9722

ColdFusion: When to define session variables?

When a user requests a page, is this when a session is started for that user? From what I can tell, a session is started as soon as you make a page request...

If this is the case, when do you create session variables? i.e. username, password, preferences, etc... just any time?

Upvotes: 2

Views: 6863

Answers (2)

Dan Roberts
Dan Roberts

Reputation: 4694

Yes the session scope for the user is setup on the first request. However it depends on your preference as to when you want to set various flags and values. You probably don't want to put password in the session scope though.

What I like to do is put user specific values in a user struct. So on request start I'd check for the variable and setup if it doesn't exist. For example...

<cfif not structkeyexists(session, "user")>
    <cfset session.user = {
        authorized = false
        , admin = false
        , username = ''
        , accountid = ''
        <!--- etc --->
    } />
</cfif>

When the user logs in you can then fill in the appropriate values and set session.user.authorized = true

When the user logs out the nice thing about this approach is you can just delete the users struct.

<cfset structdelete(session, "user") />

Then on the next page the check will be made again for the user struct and created if it doesn't exist.

Upvotes: 5

Jeremy Halliwell
Jeremy Halliwell

Reputation: 3385

The basics of configuring and using session variables are explained here.

A session is basically a logical relationship between a client and an application, so session variables are available from the client's first request to your application, and the session is typically persisted across requests using cookies which uniquely identify the session, although this can be also done by passing the identifiers in the url. It's worth paying attention to your session timeout settings, for example you may want to provide a shorter timeout to bots/crawlers which don't set cookies and will therefore initiate a new session for each page request (more details on this).

Upvotes: 5

Related Questions