Lompat ke konten Lompat ke sidebar Lompat ke footer

Perl Uploading File From Html Form !g

Uploading files using CGI and Perl.

This tutorial is intended for website programming or Perl beginners, who on one side accept the cognition to create HTML forms with the user data input fields and to write a Perl CGI-script to retrieve the user data, on the other side, do not know or are not sure how to proceed to upload a file, located on the user'southward computer to the webserver or to read the user's file and use its content within the uploading Perl script (equally this file is located on the client's computer and not on the server, I'll phone call it remote file in the following paragraphs). The tutorial concentrates on the essential, describing the basics, assuasive the readers to create their ain upload scripts with a minimum of effort, without neglecting the security issues, that file uploads may cause. The examples, used in the tutorial, are more often than not from my DNA molecular weight calculator online application.

HTML forms for file upload.

The first affair to consider is, that in club to exist able to upload a file, the form field must be defined with the special multipart/form-data encoding blazon:
<form id="form1" name="form1" activity="/cgi-bin/dna_molweight.pl" method="mail" enctype="multipart/grade-data">

We then need "some element" on the form, that gives the user the possibility to specify the file to be uploaded. This chemical element actually has to exist a file input field. If we insert <input type="file" proper name="filename" id="filename"/> into the HTML code, the result on the corresponding webpage volition be an upload push, that allows the user to browse to the file. This button (labeled Cull file in Chromium based browsers, labeled Browse... in Firefox) is followed past the text "No file selected", text that will be replaced by the name of the file, later on the user has selected one. Here the file input field definition in my Dna application (the checkbox allows to choose between manually input of a DNA sequence and uploading a DNA file) and a screenshot of the Dna application webpage, showing the respective upload push button (the user not yet having selected a file).
<input blazon="checkbox" proper name="usefile" id="usefile" value="usefile" /> Load DNA sequence from local file:   <input type="file" name="filename" id="filename"/>

DNA molecular weight calculator: Webpage with a file input field for file upload


The submit input field is the same as on other forms. When the resulting Submit button on the webpage is pushed, the proper noun of the remote file will exist passed to the CGI script, in the same way as the other user data, entered on the grade.

CGI scripts accessing remote files.

In that location is no special code needed in the CGI script to read data from a remote file. However, for evident reasons, y'all should ever limit the filesize allowed for uploads. The maximum filesize is, of class, awarding dependent. In my DNA application, I chose 25kb; if the upload consists of photos, some megabytes would be an appropriate limit. The maximum size of the file to exist uploaded may exist indicated at the beginning of the CGI script (immediately after the utilise statements), using the $CGI::POST_MAX variable (the value assigned having to be in bytes). Here the showtime lines of my DNA script:
#!/usr/bin/perl -I"."
apply strict; utilise warnings;
use CGI;
use CGI::Bother "fatalsToBrowser";
use File::Basename;
$CGI::POST_MAX = 1024 * 25;

Another thing, y'all should always do is to make sure, that the name of the upload file merely contains safe characters. This is particularly important, if you intend to store the file on the server. Characters, such equally "/" are really dangerous in filenames, every bit they might allow attackers to upload files to any directory they wanted (or at least, store it somewhere else, as the directory, that y'all wanted). The best practice is to only allow the following characters in filenames: messages, digits, underscores, hyphens, and (equally needed for file extensions) periods, eventually also spaces (converting them to underscores, before saving the file). Additional security could be given by checking the file extension; if, for example, the upload is previewed to be a photo, refuse any files, that are not .png, .jpg, .jpeg and some others.

As some browsers render not only the uncomplicated name, but the complete path of the remote file, nosotros need anyway to preview some code to split the filename into path, name and extension. A very unproblematic way to do this, is to use the fileparse function of the File::Basename module (that's the reasons for the apply File::Basename; in the code higher up.

My DNA awarding outset checks, if the Deoxyribonucleic acid has to exist read from a remote file (if the checkbox is non selected, information technology is causeless to be entered manually). If this is the case, it checks, if information technology has received a filename from the "calling webpage" (this is not the case, if the user didn't select a file, of course, but besides if the size of the file selected exceeds the limit defined at the beginning of the script). If the filename is present, the script validates it, refusing to upload any file with a name that contains one or more characters, that are not part of those, defined to a higher place, past displaying an "Invalid filename" message (the script doesn't do any extension checking, as the file content, having to exist a valid Deoxyribonucleic acid sequence, is checked character by character).
    my $fileusage = ''; my $filename = '';
my %params = $cgi->Vars;
$fileusage = $params{'usefile'}; $filename = $params{'filename'};
if ($fileusage eq 'usefile') {
if ($filename) {
my ( $name, $path, $extension ) = fileparse ( $filename, '..*' );
$filename = $name . $extension; my $filename2 = $filename;
$filename2 =~ due south/[^a-zA-Z0-9 _\.\-]//m;
if ($filename2 eq $filename) {

- read Deoxyribonucleic acid sequence from remote file -
            }
else {
$mess = "Invalid filename: $filename!";
}
}
else {
$mess = 'No filename or could not upload local Deoxyribonucleic acid file!';
}
}
else {

- get Deoxyribonucleic acid sequence from text area -
    }

Reading remote files and saving them (or not) onto the webserver.

Reading a remote file works the same way than reading a local file: using a file handle, associated with the (input) file to get its data. In the instance of a local file, the handle is created and opened by the argument open(FH, "input_filename") or dice "$!";, in the instance of a remote file, we tin can get the (opened) file handle by using the upload method of the CGI module:
my $FH = $cgi->upload("remote_input_filename");
Having the file's handle, we can use its data in exactly the same fashion as nosotros do with local files. Two examples to show the basics in the following paragraphs.

Saving a remote file onto the webserver.

This is not, what is done by my DNA application (why should I save a file that contains user data passed to the app, but not needed by myself or otherwise useful to have a re-create on the server?), but would for example be the procedure to follow in the case of a photo site, where users can upload their pictures. Just, first, we need a file upload directory. This directory may exist located anywhere within the file construction. If you lot want the pictures to be visible on your website, you have to use a subdirectory of the server's htdocs (ex: /dwelling house/public_html/htdocs/upload). In other cases (for case a photo site, where you want to view the photos, earlier they get accessible past everyone), you may prefer a directory outside the htdocs (ex: /home/photos/new). In both cases, make sure that the webserver has (read and) write permission for the upload directory (on Unix systems, a chmod 777 should work fine). The post-obit code uses the file handle, passed past the "calling website", to simply copy the remote's file content (for instance a photo) to a file on the webserver (please note, that "filename" is the HTML id of the file input field on the class).
my $upload_dir = "/home/public_html/htdocs/upload";
my $filename = $query->param("filename");
my $FH_IN = $query->upload("filename");
open up(FH_OUT, ">$upload_dir/$filename")
or die "$!";
binmode FH_OUT;
while (<$FH_IN>) {
impress FH_OUT;
}
close FH_OUT;

Reading a remote file to work with its data.

This is the case of my Dna awarding, that reads the sequence from a file, stored on the user's calculator, and uses the file'south content to calculate the molecular weight of the sequence. Plainly, no demand to save the Deoxyribonucleic acid sequence on the webserver. Here the code (once more, "filename" is the HTML id of the file input field on the course).
my $FH_IN = $query->upload("filename");
while (<$FH>) {
$alldna .= $_;
}

That's it!

Some final notes for those readers, who have no or little experience with working with files, using Perl. The variable $alldna, used in the code higher up, is a long string, that volition contain the complete content of the DNA file. This includes the terminate-of-line markers, terminating the physical lines in text files. This makes information technology easy to display the string, formatted the same way as is the text file; in the case of the Dna application, to display the formatted sequence (FASTA header in the first line, than the sequence data lines, with the same number of bases per line every bit in the file). Perhaps, you lot wonder how to do to make full a HTML text area, equally these elements have no value belongings? The page, generated by the DNA script, is based on a template HTML file, containing custom tags, that the script replaces with the actual values. Here the text area line in the template:
<td colspan="4" style="padding-top: 10px"><textarea proper noun="dna" id="dna" cols="xc" rows="fifteen">#dna#</textarea>
To fill the text area with the actual Deoxyribonucleic acid sequence, the script simply replaces the #dna# tag by the content of the $alldna variable.


levanangatte.blogspot.com

Source: https://www.streetinfo.lu/computing/website/programming/perl_upload.html

Posting Komentar untuk "Perl Uploading File From Html Form !g"