#!/usr/bin/perl # Example of how to create temporary files from CGI scripts without # clobbering existing files or breaching security with a race condition. # See "Web Security, A Step-by-Step Reference Guide" by Lincoln Stein, page 329 use FileHandle; $TMPDIR = '/usr/tmp'; # location of temporary files srand(); # randomize temp file names a bit $tempFileHandle = tempFile() or die; [Use the file handle for something] close $tempFileHandle; # will automatically be deleted sub tempFile { my $basename = 'temp'; my $seq = rand(10000); my $filename; do { $filename = sprintf("$TMPDIR/%s.%05d",$basename,$seq++); } until !-e $filename; my $fh = new FileHandle $filename,O_RDWR|O_CREAT|O_EXCL; unlink $filename; truncate $fh,0; $fh; }