10.07.2015 Views

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

80CHAPTER 4 ■ SYSTEM INTERACTIONAccessing Uploading File Header InformationThe CGI module also includes a function called uploadInfo(), which gives you access <strong>to</strong>header information which may (or may not) be sent from the web browser along with theuploaded file. The headers sent by the browser are actually sent as a reference <strong>to</strong> a hash orassociative array. Using the uploadInfo() function along with a header like Content-Type,it’s possible <strong>to</strong> determine the type of document being uploaded in order <strong>to</strong> allow only certaintypes <strong>to</strong> be uploaded. Be forewarned though, browsers can lie. Don’t ever rely on userinput or on any data coming from a user’s browser. As I’ve emphasized in previous chapters,no input should be used within your program until it has been validated.For example, it’s possible <strong>to</strong> incorporate a CGI program in<strong>to</strong> the form shown in Figure 4-1in order <strong>to</strong> print the Content-Type of the file being uploaded. Listing 4-1 contains a basic CGIscript for accomplishing this task.Listing 4-1. Printing the Content-Type of an Uploaded File#!/usr/bin/perluse strict;use CGI qw/:standard/;my $q = new CGI;my $filename = $q->param('uploaded_file');my $contenttype = $q->uploadInfo($filename)->{'Content-Type'};print header;print start_html;print "Type is $contenttype";print end_html;The Content-Type is placed in<strong>to</strong> the variable $contenttype, and then printed <strong>to</strong> the outputstream of an HTML page as an example. Figure 4-2 shows an example of choosing <strong>to</strong> uploadan HTML file, and Figure 4-3 shows the output produced from Listing 4-1.In practice, you would likely check the content type in order <strong>to</strong> make sure that it’s one of theacceptable types of files that your program expects as input. Consider the example in Listing 4-2.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!