Transmission as a whole in ColdFusion; disinfecting variables

I'm rusty in ColdFusion, I'm used to PHP for so long. I want to do something like this:

<?php $id = (isset($_GET['id'])) ? (int)$_GET['id'] : 0; ?> 

Basically, check the url parameter called id , and if it exists, make sure it is an integer, so I can safely use it in database queries. If it ends with zero, that's good too.

I have:

 <cfscript> if (IsDefined("URL.id") AND IsNumeric(URL.id)) { id = int(URL.id); } else { id = 0; } </cfscript> 

It works, but it's terribly dirty. Is there a better way to do this?

+4
source share
6 answers

I would use cfparam. I would also clearly indicate, but this is not necessary. I would not use the IIF () function because it uses the evaluation () method, which can be problematic, I would also avoid DE () for the same reason. In this case, this will not be a problem, but I avoid them as a general principle in any situation where this is not necessary. I have been using CF for several years now and it is not needed yet.

 <cfparam name="url.id" default="0" /> <cfif isNumeric(url.id)> <cfset local.id = int(url.id) /> <cfelse> <cfset local.id = 0 /> </cfif> 
+1
source

Recent versions of ColdFusion also have a ternary conditional statement:

 <cfset id = (structKeyExists(URL, "id") and isNumeric(URL.id)) ? int(URL.id) : 0> 
+10
source

For me, the easiest way to ensure that your variable is an integer is to transfer the variable to val ().

He tries to parse the string and extract any integer (at the beginning of the string). If none are 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 0 (not an error).
  • If TestValue = "0", Val (TestValue) returns 0 (not an error).

See http://cfquickdocs.com/cf8/#Val

+1
source

Apologies for collecting the old thread, but came up with the same question and found a simple solution that could help others with this problem

 NumberFormat(URL.id) 

There are also various masks that you can specify in different scenarios.

ColdFusion Reference

Formatted numeric value:

If no mask is specified, returns the value as an integer with a thousands separator. If the parameter value is "" (empty string), 0 is returned.

http://help.adobe.com/livedocs/coldfusion/8/htmldocs/help.html?content=functions_m-r_08.html

+1
source

You can also see cfparam .

 <cftry> <cfparam name="url.id" default="0" type="integer"> <cfcatch> <!--- log? etc ---> <cfset url.id = 0> </cfcatch> </cftry> 
0
source

You can use IIF . That's cool.

 <cfset id = IIf(IsDefined("URL.id") AND Int(URL.id), Int(URL.id), DE("0"))> 
-4
source

All Articles