The basic steps are as follows:
The reason for the lockfile is simple: you can't flock a file until it's opened, but by then something else might already have opened that file and done something to it. Two programs trying to access your log at the same time (say, one for reading and one for writing) could cause data corruption or a race condition. By using a lock file, you have a file that can safely be opened and flocked without worrying about whether or not it's going to get corrupted.
#!/usr/bin/perl -wT use strict; use Fcntl qw/:flock/; use CGI qw/:standard/; my $log = 'somelog.log'; my $lockfile = "$log.lock"; # grab form data my $_name = param( 'name' ); my $_email = param( 'email' ); # untaint form data my ( $name ) = ( $_name =~ /^([\w.',]{1,30})$/ ) or some_error_routine( $_name ); # I *hate* dot-star untainting, but virtually any character # is valid in an email address. my ( $email ) = ( $_email =~ /^(.{1,500})$/ ) or some_error_routine( $_name ); # We're getting rid of ASCII zero as this is the delimiter # in the file we're writing to. $email =~ s/\0//g; open LOCK, "> $lockfile" or die "Cannot open $lockfile: $!"; flock LOCK, LOCK_EX or die "Cannot flock $lockfile: $!"; open LOG, ">> $log" or die "Can't open $log for appending: $!"; print LOG "$name\0$email\n"; close LOG; close LOCK; # output some response here
Note that the above code is incomplete and untested. Further, I have limited the length of the $name and $email variables. This is done to ensure that someone doesn't try to enter unreasonably large values for this data.
Cheers,
Ovid
Vote for paco!
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
In reply to (Ovid) Re: CGI Form processing
by Ovid
in thread CGI Form processing
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |