#!/usr/bin/perl # use DBI; print "Content-type:text/html\n\n"; $dbh = DBI->connect( "dbi:mysql:usertable", "usertable", "jutedi2") or &dienice("Can't connect to db: ",$dbh->errstr); read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); @pairs = split(/&/, $buffer); @keys = (); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; push(@keys, $name); $FORM{$name} = $value; } $username = $FORM{'username'}; $password = $FORM{'password'}; $realname = $FORM{'realname'}; $email = $FORM{'email'}; # First, do some data validation. # be sure the username is alphanumeric - no spaces or funny characters if ($username !~ /^\w*$/) { &dienice("Please use an alphanumeric username, with no spaces."); } # be sure their real name isn't blank if ($username eq "") { &dienice("Please enter your real name."); } # be sure the password isn't blank or shorter than 6 chars if (length($password) < 6) { &dienice("Please enter a password at least 6 characters long."); } # be sure they gave a valid e-mail address # (this uses the email-address pattern match from chapter 14) if ($email !~ /[\w\-]+\@[\w\-]+\.[\w\-]+/) { &dienice("Please enter a valid e-mail address."); } # check the db first and be sure the username isn't already registered $sth = $dbh->prepare("select * from users where username = ?") or &dienice("Can't select from table: ",$dbh->errmsg); $sth->execute($username); @out = $sth->fetchrow; if ($#out >= 0) { &dienice("The username `$username' is already in use. Please choose another."); } # ok, it's not, so add them to the database. # we're going to encrypt the password first, then store the encrypted # version in the database. $encpass = &encrypt($password); $sth = $dbh->prepare("insert into users values(?, ?, ?, ?, ?)") or &dienice("Can't add data to user table: ",$dbh->errmsg); $sth->execute($username, $encpass, "CURRENT", $realname, $email); print <Registration Successful! You're now registered! Your username is $username, and your password is $password. Login here.

EndHTML sub encrypt { my($plain) = @_; my(@salt); @salt = ('a'..'z', 'A'..'Z', '0'..'9', '.', '/'); srand(time() ^ ($$ + ($$ << 15)) ); return crypt($plain, $salt[int(rand(@salt))] . $salt[int(rand(@salt))] ); } sub dienice { my($msg) = @_; print "

Error

\n"; print $msg; exit; }