Ruby on the web - a simple example using CGI
Archive - Originally posted on "The Horse's Mouth" - 2012-06-22 12:02:49 - Graham Ellis
Form inputs (using the default GET method) are delivered in the QUERY_STRING variable in the environment. They take the form of a series of & separated name=value pairs, which I separate out into a hash. The I have decoded the values further, as they may contain + characters for spaces, and % followed by two hex digits for other special characters. In theory, the names could be encoded in a similar way if my web page designer used special characters or spaces in field names. Also in theory, I could have multiple filed with the same name!
I have applied a further set of check on the contents of the field called search. This is done to ensure only simple literal searches to our web site visitor are offered, rather than allowing him to enter regular expressions. Of course, we're also removing the ability to search for special characters, but in a demonstration that's not really an issue.
When I echo out the value that was entered because it contains illegal search characters, I have to encode characters which mean something special to the browser within the HTML stream = & and <. In a full application I would do this on every output; in this sample, I've not done it on the data that I read from the file (as I know my data file won't change and is clean) nor on my correcly-echoed search string as I've already filtered that.