CGI / DB / TT quick example

Ranguard on 2002-09-26T13:56:48

Over the last few months several people have asked me how to create a cgi script that uses a database and then prints out the results.

Often they're just looking for an example rather than a full blown explination. So here one is http://leo.cuckoo.org/projects/cgi_db_tt_example/

Still need to write up YAPC::E! Patches / comments welcome, though it's not mean't to be perfect, it's just mean't to get people going.


Hmm...problems.

2shortplanks on 2002-09-26T14:37:53

Leo,

There are numerous issues with this code

  1. You're not using taint
  2. You're placing stuff directly into a SQL statement from a parameter without quoting it first. This is essentially letting anyone execute arbitary SQL code on your server. Use taint.
  3. You've called the name of the variable you're outputting the template to $file, even though it's just a scalar. Why are you using this anyway...just print it to STDOUT by not having a third argument
  4. Your whitespace doesn't format the code very well.
  5. You should probably be calling $q->param() in scalar context to avoid letting anyone polute your hashs (by passing name=foo;name=key;name=value)
There also are other ways to do things
  1. You could use the DBI plugin to do this.
  2. You could use an error template rather than printing the incorrect HTML.

Re:Hmm...problems.

Ranguard on 2002-09-26T15:14:04

Bad Leo, naught leo, no pie!!!!

Some updates made, will look at rest soon, my brain has just decided to start thumping and turned to a pile of goo at the same time :(

others

  1. Could use DBI plugin but didn't want to as I don't agree with it in the Template unless it's a quick hack.
  2. Guess so, but I'll leave it for now as I consider it just for debuging, though I guess a dodgy bit of user data could do something odd later.

Re:Hmm...problems.

2shortplanks on 2002-09-26T15:27:26

2. Guess so, but I'll leave it for now as I consider it just for debuging, though I guess a dodgy bit of user data could do something odd later.


Yeah, you're leaving yourself open somewhat to a cross site scripting attack. Best to use an error template (if you're going to print out anything to the browser) and do a [% error.info | html %]

more comments

gav on 2002-09-26T15:29:54

You aren't being sufficiently lazy! :)

  • bind variables, let DBI quote them for you
  • RaiseError to trap DBI errors
  • replace sql_to_array_of_hashes with $dbh->selectall_arrayref($sql, { Slice => {} }, @data)