tags:

views:

383

answers:

1

In ColdFusion, how can I determine if a variable exists within the querystring without throwing an error attempting to check it?

+14  A: 

There are two options.

The first is to use cfparam to define a default value eg:

<cfparam name="url.varname" type="string" default="" />

This ensures that you can always refer to url.varname

The second is to use isDefined or structKeyExists to test for the presence of the variable:

<cfif isDefined("url.varname") and url.varname eq 42> do something </cfif>

or

<cfif structKeyExists(url, "varname") and url.varname eq 42> do something </cfif>
Antony
one more way for CF9: isNull(url.varname)
Henry
A neat trick with cfparam is just to use name="varname" rather than name="url.varname" - then it will validate that varname exists as either a url var or a form var. Makes switching between GET and POST easy.
kevink
@kevink, that's a dangerous path to go down. If the variable isn't defined in URL or FORM scopes, then CFParam will create it in the VARIABLES scope. There are significant but nuanced side-effects of this, and you really need to be aware of what is actually happening in order to secure the reliability of your application.
Adam Tuttle
@Adam that is exactly how I expect an undefined variable to act, and it seems perfectly consistent (when the var was not actually there in the url or form scope) how has it bitten you in the past?
kevink
@kevink if you expect the variable from the URL scope, param it to the URL scope. This makes sure that the value cannot be injected from another scope. It's also possible that there could already be a variables.varname in the code that suddenly gets param'd to another value since you left the scope of off the cfparam.
iKnowKungFoo
@kevink what @iKnowKungFoo said is exactly right. You should use: `<cfparam name="url.foo" default="bar" />` so that the variable is put into the scope where you are expecting it to be. Then, your handling code uses `url.foo`, not just `foo`.
Adam Tuttle
Take it one further, if you want the variable to be insensitive: <cfparam name="url.foo" default="" /> <cfparam name="form.foo" default="#url.foo#"/>: This will ensure that foo exists in both the url and form scopes, and you could just always reference, say, the 'form.foo' variable, but will be assured that you can hit the page directly with URL params.
Shawn Grigson