Dylan
Dylan

Reputation: 593

Perl: Handing $dbh off to module. Security and performance?

So I have a cgi script,

#!/usr/bin/perl -T

use strict;
use warnings;
use DBI;
use WebEngine;


my $dbh = DBI->connect('DBI:mysql:database', $username, $password)
    || die "Could not connect to database: $DBI::errstr";

my $we = WebEngine->new($dbh)
    or die("Failed to instantiate WebEngine object:\n$!\n");

$userID = $we->register("MyUsername", $dbh);

This script creates a database handler and then uses a module I made to deal with most of the back-end of the site to register a username and return a userID number.

I have three questions about this.

Upvotes: 1

Views: 419

Answers (2)

dan1111
dan1111

Reputation: 6566

Does creating this $dbh in this script increase performance by keeping a database connection open?

Could I put the $dbh in my module and not fear being inefficient?

Generally, you want to minimize the length of time that a database connection is open. Having lots of connections open at the same time hurts performance. The longer you keep a connection open, the more connections you will accumulate when lots of people use your site at the same time.

On the other hand, disconnecting and reconnecting many times could also hurt performance.

If you expect a large traffic volume on your site, the best solution is to implement connection pooling. This keeps a number of active connections open and available, but doesn't tie them to a particular user. Here is a discussion of MySQL connection pooling with Perl. If you implement it this way, then you would want to open a connection for the minimum time possible. It will be efficient, because it isn't a "real" open under the hood--just an assignment of an already-open connection.

Is there a security benefit to keeping the $dbh (and the associated info(I keep my pass in plain text in the code; is that bad?)) in the module that is not directly interacted with through my website?

If the module is located in a non-web-accessible folder, that might be a slight benefit. Really, though, you should not be storing a password in plain text. Here is a discussion of some other options.

Upvotes: 3

January
January

Reputation: 17110

You can create static variables in your module, or go full OO and create module objects that initialize $dbh internally and keep it alive. There will be no performance impact on doing that.

As for the interaction with external data -- your module is just another way of packaging the code, so it is as likely (or unlikely) to be exploited as your main code. You should rely on other precautions (such as using tainted mode).

Upvotes: 0

Related Questions