Cast as integer in ColdFusion; sanitizing variables
I'm rusty at ColdFusion, I've been used to PHP for so long. What I want to do is something like this:
<?php
$id = (isset($_GET['id'])) ? (int)$_GET['id'] : 0;
?>
Basically, check for a url parameter called id
and if it exists make sure it's an integer so I can safely use it in database qu开发者_StackOverflow社区eries. If it ends up zero, that's fine too.
I have:
<cfscript>
if (IsDefined("URL.id") AND IsNumeric(URL.id)) {
id = int(URL.id);
} else {
id = 0;
}
</cfscript>
This is working, but is awfully messy. Is there a better way to do this?
Recent versions of ColdFusion also have a ternary conditional operator:
<cfset id = (structKeyExists(URL, "id") and isNumeric(URL.id)) ? int(URL.id) : 0>
I would use cfparam. I'd also scope explicitly, but that's not necessary. I wouldn't use the IIF() function, because it makes use of evaluate(), which can be problematic, I'd also avoid DE() for the same reason. In this case, it won't be an issue, but I avoid them on general principle in any situation where it's not absolutely necessary. I've been using CF for a few years now, and it hasn't been necessary yet.
<cfparam name="url.id" default="0" />
<cfif isNumeric(url.id)>
<cfset local.id = int(url.id) />
<cfelse>
<cfset local.id = 0 />
</cfif>
To me, the simplest way to ensure your variable is an integer is to wrap the variable in val().
It attempts to parse the string and extract any integer found (at the beginning of the string). If none is found it returns 0.
- If TestValue = "234A56?7'", Val(TestValue) returns 234.
- If TestValue = "234'5678'9?'", Val(TestValue) returns 234.
- If TestValue = "BG234", Val(TestValue) returns the value 0, (not an error).
- If TestValue = "0", Val(TestValue) returns the value 0, (not an error).
See http://cfquickdocs.com/cf8/#Val
Apologies for raising an old thread but came up with this same question and found a simple solution that might help others with this issue
NumberFormat(URL.id)
There are also various masks that you can specify in different scenarios
ColdFusion Reference
A formatted number value:
If no mask is specified, returns the value as an integer with a thousands separator. If the parameter value is "" (an empty string), returns 0.
http://help.adobe.com/livedocs/coldfusion/8/htmldocs/help.html?content=functions_m-r_08.html
You might also look into cfparam
.
<cftry>
<cfparam name="url.id" default="0" type="integer">
<cfcatch>
<!--- log? etc --->
<cfset url.id = 0>
</cfcatch>
</cftry>
You can use IIF
. It's cool.
<cfset id = IIf(IsDefined("URL.id") AND Int(URL.id), Int(URL.id), DE("0"))>
精彩评论