Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

question about allowing user to upload files (image) to my server...

Status
Not open for further replies.

spewn

Programmer
May 7, 2001
1,034
i found this code online:

Code:
#!/usr/bin/perl -wT 

use strict; 
use CGI; 
use CGI::Carp qw ( fatalsToBrowser ); 
use File::Basename; 
$CGI::POST_MAX = 1024 * 5000; 
my $safe_filename_characters = "a-zA-Z0-9_.-"; 
my $upload_dir = "/home/mywebsite/htdocs/upload"; 
my $query = new CGI; 
my $filename = $query->param("photo"); 
my $email_address = $query->param("email_address"); 
if ( !$filename ) 
{ 
 print $query->header ( ); 
 print "There was a problem uploading your photo (try a smaller file)."; 
 exit; 
} 
my ( $name, $path, $extension ) = fileparse ( $filename, '\..*' ); 
$filename = $name . $extension; 
$filename =~ tr/ /_/; 
$filename =~ s/[^$safe_filename_characters]//g; 
if ( $filename =~ /^([$safe_filename_characters]+)$/ ) 
{ 
 $filename = $1; 
} 
else 
{ 
 die "Filename contains invalid characters"; 
} 
my $upload_filehandle = $query->upload("photo"); 
open ( UPLOADFILE, ">$upload_dir/$filename" ) or die "$!"; 
binmode UPLOADFILE; 
while ( <$upload_filehandle> ) 
{
 print UPLOADFILE; 
}
close UPLOADFILE;

works great, with one exception.

i want to name the file a unique name, yet it seems to be saving the file with the image name and the entire path:

such as: CDocuments_and_SettingsCompAdminDesktopfoldernamesubfoldername1234567-2

also, i have another question/concern:

how can i alter this (if needed) so that a user cannot upload a malicious script and either hack or crash my server.

is this even possible?

new to this, so i want to know what is/isn't possible.

thanks!

- g
 
The problem with saving the filename with the directory path is that File::Basename assumes a file path type native to the operating system its installed on. But since you want to rename the saved file you won't have to worry about that.

An easy way to name a file is use the value of time. Unless your site is very busy that should be fine.

my $filename = time;

As far as filtering what type of files can be uploaded that is more involved. How you do it depends on how strictly you want to try and filter files. You can look into a module like MIME::Types to try and determine the file type and allow the ones you want (images) and reject everything else.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top