Question

Determining if a file exists (PERL)

Asked by: DavidLeeding

Hi

Although I have a background in programming, PERL is completely new to me...and I'm getting nowhere fast!! Hoping you can help!

I have obtained a PERL script that is used in conjunction with a web form to upload a customer's file (or files) to a server. The script is working perfectly except for one flaw...if the user's file does not exist locally (eg the user typed an invalid file name), the script still acts as though the file *was* uploaded successfully. In fact, it creates a zero-length file on the server, and reports to the user that the file was uploaded.

Ideally, I'd like the script to fail gracefully if the filename does not exist locally.

Can this be done???

The following is an extract of the script to give you some context. I have marked the area where I think (?) the appropriate test would go (assuming there is something that can be done).

$ERROR_BADFILE = "/ord_err1.htm";
$SAVE_DIRECTORY = "/home/usrname/www/orders";
...
$| = 1;
chop $SAVE_DIRECTORY if ($SAVE_DIRECTORY =~ /\/$/);
use CGI qw(:standard); # Script uses CGI.pm
$query = new CGI;

foreach $key (sort {$a <=> $b} $query->param()) {
    next if ($key =~ /^\s*$/);
    next if ($query->param($key) =~ /^\s*$/);
    next if ($key !~ /^file-to-upload-(\d+)$/);
    $Number = $1;
            
    if ($query->param($key) =~ /([^\/\\]+)$/) {
        $Filename = $1;
        $Filename =~ s/^\.+//;
        $File_Handle = $query->param($key);

#### --> Test in here? if ( ! (file exists locally)) {
####       redirect to error page (ie $ERROR_BADFILE)
####       then exit

    } else {
        print $query->redirect($ERROR_BADFILE);
        exit;
    }

Hoping someone can enlighten me!!

Thanks

David

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-03-09 at 04:25:02ID20912237
Tags

perl

,

file

,

exists

Topic

CGI Scripting

Participating Experts
6
Points
0
Comments
13

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Using Wget with CGI/Perl
    why is it that i can't get my CGI script (in perl) to grab a file off a http site? in my script i have system("wget -P /mydir $mysite"); i get no errors, but the files dont copy and if i go system("wget -P /mydir $mysite > log"); i get no log either?...
  2. Perl CGI
    Hi... i have this cgi code which is suppose to upload file to the internet, but it don seem to appear in the web browser, instead it show me the code which i've written. did i place my code at the wrong directory or that this code do not have a html output? btw i am using p...
  3. PERL CGI variables to $FORM{}
    I was using... read(STDIN, $buf, $ENV{'CONTENT_LENGTH'}); $str= "$ENV{'QUERY_STRING'}&$buf"; @pairs=split('&',$str); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C&qu...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: dorwardPosted on 2004-03-09 at 05:05:37ID: 10549722

To test if a file exists:

(-f $path_to_file)

 

by: rkosaiPosted on 2004-03-09 at 12:36:30ID: 10554354

Actually, that comment above is incorrect. The correct syntax is  (-e $path_to_file)

-f is the flag used to determine if the file is a "plain" file (versus a directory or symbolic link).

So, to find if the file "/test.txt" exists, you would use the code:

if (-e "/test.txt") {
  print "File Exists.\n";
}

 

by: TintinPosted on 2004-03-09 at 14:26:44ID: 10555473

That code sample you supplied is very confused, particularly with the use of the CGI module as it mixes the two interfaces.

 

by: DavidLeedingPosted on 2004-03-09 at 16:08:53ID: 10556244

Thanks for the repsonses so far. At least I now know what -e and -f mean!!

I've seen the -e (as in rkosai's comment) used in PERL scripts before (although I could only guess at what it meant)...but used in the context of files/paths on the *server* where the PERL script is run. My problem is in working out whether the file the user is uploading actually exists at *their end*.

Perhaps the issue for me is working out how to extract the path/filename from the existing code (see original post). I have now tried code along the lines of:

if (-e $Filename) {
  print "File Exists.\n";
}

...but the local file is not found even when it exists. Am I on the right track? (Or am I asking for the impossible?)

Perhaps the issue is in knowing how to specify that the file/path being tested is *not* on the server (if this can be done).

Regarding Tintin's comment...the code snippet I used is only a small section of the total script. I didn't write the script...I just want to correct a problem with it. If you are interested in the full script, you can obtained it from:

members.ozemail.com.au/~davidml/test/upload.zip .

Sorry if this question is a bit naive! This thing called PERL is still new to me and somewhat daunting!!

 

by: TintinPosted on 2004-03-09 at 16:27:53ID: 10556396

OK, what you want to achieve is possible, but certainly not desirable or reliable.  Essentially the only way you can check for a file existance on users local machine (in the web context) is to use a Javascript/ActiveX combo.  This won't work in all browsers, platforms and is generally disabled as a security risk.

One small nitpick.  The language is Perl not PERL.  From the Perl FAQ

What's the difference between "perl" and "Perl"?

     One bit.  Oh, you weren't talking ASCII? :-) Larry now uses
     "Perl" to signify the language proper and "perl" the
     implementation of it, i.e. the current interpreter.  Hence
     Tom's quip that "Nothing but perl can parse Perl."  You may
     or may not choose to follow this usage.  For example,
     parallelism means "awk and perl" and "Python and Perl" look
     OK, while "awk and Perl" and "Python and perl" do not.  But
     never write "PERL", because perl isn't really an acronym,
     apocryphal folklore and post-facto expansions
     notwithstanding.

 

by: ahoffmannPosted on 2004-03-10 at 07:03:23ID: 10561199

$Filename =~ s/^\.+//;   # this is insecure !!
 $Filename =~ s#([^a-z0-9_+\.-])##ig;  # this is strong
# if you allow / you may add it in the characterclass
 $Filename =  './' . $Filename;     # just in case someone tries nasty things
if (-e $Filename) { print "exists"; }

# NOTE that my suggestion is very, very unsafe if you add something like ><|;%&$ to the characterclass

 

by: DavidLeedingPosted on 2004-03-11 at 02:54:05ID: 10569931

(Apologies for the sin of calling Perl "PERL" :-) )

Still struggling with this. It just seems to me that if the script can get a handle on the local file in order to copy it, there must be some way for it to work out during an attempted read that there's nothing to copy.

The part of the script which I assume does the actual copying is below. Perhaps this is where the error handling needs to be done:

undef $BytesRead;
undef $Buffer;
while ($Bytes = read($File_Handle,$Buffer,1024)) {
    $BytesRead += $Bytes;
    binmode OUTFILE;
    print OUTFILE $Buffer;
}
push(@Files_Written, "$SAVE_DIRECTORY\/$Filename");
$TOTAL_BYTES += $BytesRead;
$Confirmation{$File_Handle} = $BytesRead;
close($File_Handle);
close(OUTFILE);

Here's why I need the script to test the vaidity of the local file...if a customer attempts to upload a file, and makes a mistake in typing the file name, the script (as it stands) reports back with "File Uploaded!". The customer then goes along thinking all is right in the world, until two weeks later when they wonder why their job isn't completed yet, and they discover that the vendor never received the upload. Not good for customer relations!

Hence my desire to find a fix .... or a better script!

 

by: dorwardPosted on 2004-03-11 at 02:57:34ID: 10569954

> It just seems to me that if the script can get a handle on the local file in order to copy it,

The script doesn't get a handle on the local file. The _browser_ gets the file, encodes it in the HTTP request and sends it to the web server. The CGI script reads it from there, not from the client machine.

 

by: DavidLeedingPosted on 2004-03-11 at 03:01:50ID: 10569975

I think I've got a solution...

undef $BytesRead;
undef $Buffer;
$i = 0;  # Initialise a loop counter
while ($Bytes = read($File_Handle,$Buffer,1024)) {
    $BytesRead += $Bytes;
    binmode OUTFILE;
    print OUTFILE $Buffer;
    $i += 1;  # increment counter
}
# Here's the new bit....
if (($Bytes == 0) && ($i == 0)) {
 # if Nothing read AND first iteration
    print $query->redirect($ERROR_BADFILE);
    close($File_Handle);
    close(OUTFILE);
    exit;
}

Testing has shown that this throws up the error page if the local filename is invalid, but succeeds if the filename is correct. Not particularly graceful, but it works!!

 

by: xfvgdrthbdtyvhgscvPosted on 2004-03-15 at 14:50:20ID: 10601867

In your description you mention the user typing the file name into the form.  I believe this is the root of the problem.

It's not a Perl problem at al, but an html form problem  Instead of having the user type the file and path into the form, use the <input type="form"> form element.

<form><input type="file" name="upfile"></form>

This places a text box and an associated "Browse..." button in your form.  Upon clicking "Browse...", the windows browser dialog is opened allowing the user to browse to the desired file, thereby negating any possibility of entry error.  You could even add some javascript to specifically stop the user from typing an entry in and forcing them to use Browse...

 

by: DavidLeedingPosted on 2004-03-15 at 15:39:16ID: 10602136

Thanks. I am aware of this strategy...in fact I am using the type="file" form object for the page in question. The problem was that *without* using javascript to prevent user changing the field, there is always a risk of a bogus file name. And I didn't want to rely heavily on javascript (due to reliability issues). So I was wanting a solution that checked the file name at the back end...just in case. The code I've come up with seems to be working quite well.

 

by: NetminderPosted on 2004-06-07 at 21:55:19ID: 11256626

User resolved; closed, 500 points refunded.

Netminder
Site Admin

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...