Checking folder and file size?

bsexton
bsexton used Ask the Experts™
on
Good Morning,

I'm new to the experts-exchange and new to perl. I have a basic script whis allows the client to upload a file(s) and creates a unique folder(directory) based on the email entered.  All that works fine.

I would like to be able to check and limit the overall folder size and issue an alert if they try to exceed it. I've tried a couple of bulletin boards and searched for scripts to lok at but am at a standstill. The script is listed below, if someone would like to just make changes to it.

I'm desperate, thanks for the help.

#!/usr/bin/perl -w
use CGI;

$upload_dir = "/home/bsexton/public_html/NEWClients";

@valid = ('theartistloft.com');
$maxfilesize = "200";
$query = new CGI;

$comments = $query->param("Comments");
$filename = $query->param("file_name");  
$email_address = $query->param("email_address");

#! try to create directory
$upload_dir = "/home/bsexton/public_html/NEWClients/$email_address";
unless (-d "$upload_dir"){
mkdir ("$upload_dir", 0777);
chmod(0777, "$upload_dir");
}
#! end of create directory

$filename =~ s/.*[\/\\](.*)/$1/;

$upload_filehandle = $query->upload("file_name");

open UPLOADFILE, ">$upload_dir/$filename";
  while ( <$upload_filehandle> )
{
   
print UPLOADFILE;

}

close UPLOADFILE;

$filename1 = $query->param("file_name1");  
$filename1 =~ s/.*[\/\\](.*)/$1/;

$upload_filehandle = $query->upload("file_name1");

open UPLOADFILE, ">$upload_dir/$filename1";
  while ( <$upload_filehandle> )
{
   
print UPLOADFILE;

}

close UPLOADFILE;

$filename2 = $query->param("file_name2");  
$filename2 =~ s/.*[\/\\](.*)/$1/;

$upload_filehandle = $query->upload("file_name2");

open UPLOADFILE, ">$upload_dir/$filename2";
  while ( <$upload_filehandle> )
{
   
print UPLOADFILE;

}

close UPLOADFILE;

$filename3 = $query->param("file_name3");  
$filename3 =~ s/.*[\/\\](.*)/$1/;

$upload_filehandle = $query->upload("file_name3");

open UPLOADFILE, ">$upload_dir/$filename3";
  while ( <$upload_filehandle> )
{
   
print UPLOADFILE;

}

close UPLOADFILE;


print $query->header ( );

#! Check Folder Size

$dirsize = 0;
#!$dirsize = dir_size($upload_dir);

#! End of Folder Check

$from = 'sales@theartistloft.com';
$subject = 'New Artist Loft Signup';

open(MAIL, "|/usr/sbin/sendmail -t");
print MAIL "To: $email_address\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
print MAIL "Dear Client:\n\n";
print MAIL "Thank you for signing up for The Artist Loft.\n\n";
print MAIL "This message is to confirm your transmission of $filename, $filename1, $filename2, $filename3 from your PC today.\n\n";
print MAIL "Your Comments: $comments\n\n";
print MAIL "For future upload modifications and use of the chatroom, please use the following information.\n\n";
print MAIL "Username = XXXXXXX\n";
print MAIL "Password = XXX\n\n";
print MAIL "REMEMBER: username and password are case sensitive\n\n";
print MAIL "Thank you.\n";
print MAIL "Sales Department\n";
print MAIL "The Artist Loft\n";
close(MAIL);

$to = 'newclient@theartistloft.com';
$from = 'sales@theartistloft.com';
$subject = 'A New Artist Loft Cleint';

open(MAIL, "|/usr/sbin/sendmail -t");
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
print MAIL "Dear Sales Department:\n\n";
print MAIL "This message is to confirm transmission of $filename, $filename1, $filename2, $filename3 from our new client $email_address today.\n\n";
print MAIL "Client Comments: $comments\n\n";
print MAIL "The Artist Loft\n\n";
print MAIL "Size of Directory $email_address = $dirsize\n";
close(MAIL);

print <<END_HTML;

<HTML>
<HEAD>
<TITLE>Thanks!</TITLE>
</HEAD>

<BODY>

<P align="center">&nbsp;</P>

<P align="center"><b><font size="5">Thanks for uploading your file!</font></b></P>
<P align="center"><b><font size="4">Your email address: $email_address</font></b></P>
<P align="center"><b><font size="4">Your file(s): $filename, $filename1, $filename2, $filename3</font></b></P>


</BODY>
</HTML>
END_HTML


Sincerely,

Bob sexton



























































































































Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Well your in luck, what your trying to do isn't really that difficult with the File::Find module.  To get the size of the upload directory and print error:

use File::Find;
my $total_size = 0;

find(sub { $total_size += -s }, @ARGV ? @ARGV : '.');

print "Total size: $total_size\n";

if ($total_size >= 200) {
   print "You have exceded your limit for the $upload_dir directory\n";
}

Let me know if you have any problems with implementing this!

bW

Author

Commented:
Good Morning,

The script seems to run, but what is the value of the $total_size.

I uploaded 4 files for a total of 1760 bytes and it returns a value of 55211? Do I need to convert something?

Also once I get the 'exceede' error, can I just exit the script?
$total_size is obtained from the -s operator, which returns the size of each file.  If thats not working for you I recomend stat[7] which also returns file size.

ex.
find(sub { $total_size += stat[7] }, @ARGV ? @ARGV : '.');

Try that let me know if you get the same result.

To answer your second question, you can end the script by using die.

if ($total_size >= 200) {
    die "You have exceded your limit\n";
}

Hope that helps!

bW
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

Author

Commented:
Good Morning,

The result of the above was a value of zero(0).

If you can respond ASAP, it would be greatly appreciated. I'm trying to launch a website and this is the last item to fix.

Thanks,
Bob
OK, I found my script I wrote about 4 months ago where I got the size of a file and converted it to Kilobytes or Megabytes if it was bigger than a Meg.

$filesize = -s $filename; #in bytes
$filesize = ($filesize / 1024); #in Kilobytes
$size = "KB";
if($filesize > 1024){
    $filesize = ($filesize / 1024); #in Megabytes
    $size = "MB";
}
$filesize = sprintf( "%.1f", $filesize );

So in your case $total_size would be in bytes.

I'm sorry about my previous stat, it should have been:

$total_size += (stat _)[7];

Let me know if any of that helps or not.

bW

So the first part of my post, was to answer your question b4:

You shouldn't need to convert because its already in bytes, its possible that 55211 is the size of your whole directory structure and not that one individual directory, if that's the case let me know and we'll get it to only get the size of that one directory.

bW
I hate to post 3 times in a row but it bothers me when i give a bad answer...so I wrote this and tested it real quick:

#!/opt/perl/bin/perl
use File::Find;

$File::Find::dir = "/directory/cgi-fies/dir";

my $total_size = 0;

find(sub { $total_size += -s }, @ARGV ? @ARGV : '.');

print "Total size: $total_size\n";

Ok this program successfully gets the size of all the files in the /directory/cgi-files/dir in bytes.  I only had two files in there so it printed out:

Total size: 9290

So I guess I forgot to mention the $File::Find::dir, sorry about that sometimes I assume too much.  Good luck with your new site!

bW

Author

Commented:
Well, here is my version of your code above. It returned a value of 55314 where the directory only has 4 small files totaling 1760 bytes. It looks like your code, yes?


#! Check Folder Size

use File::Find;

$upload_dir = "/home/bsexton/public_html/NEWClients/$email_address";

$File::Find::dir = $upload_dir;
my $total_size = 0;

find(sub { $total_size += -s }, @ARGV ? @ARGV : '.');

if ($total_size >= $maxfoldersize) {
die "You have exceded your limit of $maxfoldersize KB for the directory
$email_address \n";
}

#! End of Folder Check

Hum, I dunno where the 55314 could be coming from, its obviously getting it from somewhere.  Your code looks correct.  Try taking out $email_address and checking a static directory.  If that works successfully, that points to a problem with $email_address.

As an aside what platform is your server running on?

bW

Author

Commented:
The operating system is Linux
Apache Server 1.3.27(unix)
Perl 5.006001

I tried taking out the $email_address. No differnce!

Bob
I dunno Bob, the only thing I can think of is having you you run just that program I posted above, see if that gets a directory's size.  Don't try just one directory, try a few.  That really should work.  If that works and your full program doesn't I'd have to ask that you post your entire program.

bW

Author

Commented:
Here is the entire script.
I tried 3-4 different directories and get the same results.



#!/usr/bin/perl -w
use CGI;

$upload_dir = "/home/bsexton/public_html/NEWClients";

@valid = ('theartistloft.com');
$maxfoldersize = "200000";
$query = new CGI;

$comments = $query->param("Comments");
$filename = $query->param("file_name");  
$fsize = -s $filename;
$email_address = $query->param("email_address");

#! try to create directory
$upload_dir = "/home/bsexton/public_html/NEWClients/$email_address";
unless (-d "$upload_dir"){
mkdir ("$upload_dir", 0777);
chmod(0777, "$upload_dir");
}
#! end of create directory

$filename =~ s/.*[\/\\](.*)/$1/;

$upload_filehandle = $query->upload("file_name");

open UPLOADFILE, ">$upload_dir/$filename";
  while ( <$upload_filehandle> )
{
   
print UPLOADFILE;

}

close UPLOADFILE;

$filename1 = $query->param("file_name1");  
$fsize1 = -s $filename1;
$filename1 =~ s/.*[\/\\](.*)/$1/;


$upload_filehandle = $query->upload("file_name1");

open UPLOADFILE, ">$upload_dir/$filename1";
  while ( <$upload_filehandle> )
{
   
print UPLOADFILE;

}

close UPLOADFILE;

$filename2 = $query->param("file_name2");  
$fsize2 = -s $filename2;
$filename2 =~ s/.*[\/\\](.*)/$1/;

$upload_filehandle = $query->upload("file_name2");

open UPLOADFILE, ">$upload_dir/$filename2";
  while ( <$upload_filehandle> )
{
   
print UPLOADFILE;

}

close UPLOADFILE;

$filename3 = $query->param("file_name3");  
$fsize3 = -s $filename3;
$filename3 =~ s/.*[\/\\](.*)/$1/;

$upload_filehandle = $query->upload("file_name3");

open UPLOADFILE, ">$upload_dir/$filename3";
  while ( <$upload_filehandle> )
{
   
print UPLOADFILE;

}

close UPLOADFILE;

$todays_upload = $fsize + $fsize1 + $fsize2 + $fsize3;

print $query->header ( );

#! Check Folder Size

use File::Find;

$upload_dir = "/home/bsexton/public_html/NEWClients/$email_address/";

$File::Find::dir = $upload_dir;
my $total_size = 0;

find(sub { $total_size += -s }, @ARGV ? @ARGV : '.');

if ($total_size >= $maxfoldersize) {
die "You have exceded your limit of $maxfoldersize KB for the directory
$email_address \n";
}

#! End of Folder Check

$from = 'sales@theartistloft.com';
$subject = 'New Artist Loft Signup';

open(MAIL, "|/usr/sbin/sendmail -t");
print MAIL "To: $email_address\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
print MAIL "Dear Client:\n\n";
print MAIL "Thank you for signing up for The Artist Loft.\n\n";
print MAIL "This message is to confirm your transmission of $filename, $filename1, $filename2, $filename3 from your PC today.\n\n";
print MAIL "Your Comments: $comments\n\n";
print MAIL "For future upload modifications and use of the chatroom, please use the following information.\n\n";
print MAIL "Username = The Artist Loft\n";
print MAIL "Password = demo\n\n";
print MAIL "REMEMBER: username and password are case sensitive\n\n";
print MAIL "Thank you.\n";
print MAIL "Sales Department\n";
print MAIL "The Artist Loft\n";
close(MAIL);

$to = 'newclient@theartistloft.com';
$from = 'sales@theartistloft.com';
$subject = 'A New Artist Loft Cleint';

open(MAIL, "|/usr/sbin/sendmail -t");
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
print MAIL "Dear Sales Department:\n\n";
print MAIL "This message is to confirm transmission of $filename($fsize), $filename1($fsize1), $filename2($fsize2), $filename3($fsize3) from our new client $email_address today. Todays total was $todays_upload bytes.\n\n";
print MAIL "Client Comments: $comments\n\n";
print MAIL "The Artist Loft\n\n";
print MAIL "Size of Directory $email_address = $total_size\n";
close(MAIL);

print <<END_HTML;

<HTML>
<HEAD>
<TITLE>Thanks!</TITLE>
</HEAD>

<BODY>

<P align="center">&nbsp;</P>

<P align="center"><b><font size="5">Thanks for uploading your file!</font></b></P>
<P align="center"><b><font size="4">Your email address: $email_address</font></b></P>
<P align="center"><b><font size="4">Your file(s): $filename, $filename1, $filename2, $filename3</font></b></P>


</BODY>
</HTML>
END_HTML









































































































































































Do you have a link where I can get the HTML front end for this, I don't want to have to make one up if I don't have to.

Everything looks good, except a bad programming habbit with $upload_dir.  I see you set that 3 seperate times so it's posible that its getting /home/bsexton/public_html/NEWClients/ instead of /home/bsexton/public_html/NEWClients/$email_address.  try using $upload_dir1, $upload_dir2, and $upload_dir3 to eliminate that possiblity.  Also could you do a search on your server for directories about the size of 55314 or whatever the size it is now...its possible that perl is only seeing the CWD or the cgi-bin directory.  If the size is unchanging no matter what directory you specify its probably a related issue.  Let me know how it goes.

bW

Author

Commented:
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns="http://www.w3.org/TR/REC-html40">

Good Evening,

I pasted in the HTML fronend form, because I have the right mouse click to view the source locked on the actual site.

<head>

<meta name="GENERATOR" content="Microsoft FrontPage 5.0">

<meta name="ProgId" content="FrontPage.Editor.Document">

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

<link rel="File-List" href="Up_Load_files/filelist.xml">


<title>Up-Load Page</title>

<!--[if !mso]>
<style>
v\:*         { behavior: url(#default#VML) }
o\:*         { behavior: url(#default#VML) }
.shape       { behavior: url(#default#VML) }
</style>
<![endif]-->
<SCRIPT LANGUAGE="JavaScript">

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Begin
function checkEmail(myForm) {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.email_address.value)){
return (true)
}
alert("Invalid E-mail Address! Please re-enter.")
return (false)
}
//  End -->
</script>
<!--[if gte mso 9]>
<xml><o:shapedefaults v:ext="edit" spidmax="1027"/>
</xml><![endif]-->
</head>



<body bgcolor="#CCCCCC">

<FORM ACTION="cgi-bin/Upload.cgi" METHOD="post" ENCTYPE="multipart/form-data" onsubmit="return checkEmail(this);return FrontPage_Form1_Validator(this)" language="JavaScript" name="FrontPage_Form1"><BR>

<p align="center"><u><b><font size="5" color="#000000">

  The Artist Loft </font></b><font size="5"><b>Up-Load Page</b></font></u></p>

<p align="center"><!--[if gte vml 1]><v:rect id="_x0000_s1025"
 alt="" style='position:absolute;left:29.25pt;top:50.25pt;width:390pt;height:51pt;
 z-index:1' fillcolor="#f60">
 <v:textbox>
<div align="center">
  <center>
  <table cellspacing="0" cellpadding="5" width="492" height="100%" bordercolor="#FFFF00" style="border-collapse: collapse">
    <tr>
      <td align="center" bordercolor="#FFFF00" bgcolor="#FFFF00" width="492"><b>
      Prepare your file in any popular program (MS Word, Frontpage etc), insert
      pictures, email links etc. and save as a web page (HTML format). Total
      file size should not exceed <u>200KB</u>. </b></td>
    </tr>
  </table>
  </center>
</div>
 </v:textbox>
</v:rect><![endif]--><![if !vml]><span style='mso-ignore:vglayout;position:
absolute;z-index:1;left:38px;top:66px;width:526px;height:74px'><img width=526
height=74 src="Up_Load_files/image001.gif" v:shapes="_x0000_s1025"></span><![endif]></p>

<p align="center"> </p>

<p align="center"> </p>

  <p><b>This page is designed for those with access to a computer and sufficient

  knowledge to create a page on there system for uploading to The Artist

  Loft. If you have your page created find it and press Submit to upload it. If
  you need to upload more than four(4) files you should do so from the Upload
  link on the side bar, after you have received the username/password in the
  email which you will be sent. If you have need for additional help, please use
  the comment area.</b></p>



<p align="center">



<FONT face="Courier New, monospace" size=3><CODE>            First to Upload:

  <INPUT

TYPE="file" NAME="file_name" size="20" tabindex="1"></CODE></FONT> </p>



<p align="center">



<FONT face="Courier New, monospace" size=3><CODE>          
Second to Upload:

  <INPUT

TYPE="file" NAME="file_name1" size="20" tabindex="2"></CODE></FONT> </p>



<p align="center">



<code>            Third</code><FONT face="Courier New, monospace" size=3><CODE>
to Upload:

  <INPUT

TYPE="file" NAME="file_name2" size="20" tabindex="3"></CODE></FONT> </p>



<p align="center">



<FONT face="Courier New, monospace" size=3><CODE>          
Fourth to Upload:

  <INPUT

TYPE="file" NAME="file_name3" size="20" tabindex="4"></CODE></FONT> </p>

<p align="left">



<FONT face="Courier New, monospace" size=3><CODE>                  Your Email Address:
<!--webbot bot="Validation" b-value-required="TRUE" --><INPUT

TYPE="text" NAME="email_address" size="20" tabindex="5"></CODE></FONT> </p>

<p align="center">

<p align="center"><textarea name="Comments" rows="8" cols="52" tabindex="6"></textarea></p>

  <p align="center">

<b><font size="1" color="#FF0000">Make very sure your Email is correct, or you
will not receive the follow-up emails or proper credit for the files sent </font></b></p>

  <p align="center">

<font size="1" color="#FF0000"><b>It is also the folder name where your files
will be uploaded!!!</b></font><b><font size="1" color="#FF0000">.</font></b></p>
  </p>

<p align="center">



<FONT face="Courier New, monospace" size=3><CODE>

<INPUT TYPE="submit"

NAME="Submit" VALUE="Upload" tabindex="7"></CODE></FONT> </p>



<script language=JavaScript>

<!--

var message="Viewing the Source is not Allowed!";





    function click(e) {





        if (document.all) {





            if (event.button == 2) {

            alert(message);

            return false;

        }

    }





        if (document.layers) {





            if (e.which == 3) {

            alert(message);

            return false;

        }

    }

}





    if (document.layers) {

    document.captureEvents(Event.MOUSEDOWN);

}

document.onmousedown=click;

// -->

  </script>





</body>



</html>

Author

Commented:
Hello,

I eliminated the other two $upload_dir, better programming but no change in value.

I changed the $upload_dir temporarily to a couple of higher up directories, no change.

I don't have access a my host to check so I posted an urgent request to the 24/7 support, explaining the situation, giving the affected code etc. and asking for them to check.  I mentioned about maybe just rading the CWD etc.

I'll let you know what their reply is.

Thanks,

Bob

Author

Commented:
Good Morning,

The analyst at the my host site responded. There is only one file near that value. It is a flash movie embedded in my index.htm, so it's probably not that?

Bob
Hum, I tryed to get your script to work on my website...but I'm having issues somewhere and didn't have time today to play with it.  I'll probably try again tonight or tomorrow.  

But in the meantime since your new to Perl I thought I might point you to the best perl site on the net, www.Perlmonks.com.  Now these guys eat, sleep, and breathe this stuff.  If I were you, I would create an account and post a very detailed question there.  Post the code that's giving you the problem, and tell them all the methods you have tried to resolve the issue.  You'll be surprised how quickly they respond, and more then likely they'll find something I'm missing.  Also you might want to provide a link to this page, whereby they can see all the steps you've done.

bW

Author

Commented:
Per you sugestion I asked the Perl Monks.  The best answer so far follows.

The problem, as identified by dws and tadman is that the use of File::Find is completely wrong.

The line $File::Find::dir = $upload_dir; is having no effect whatsoever and is not intended for use this way.

When you call find(), you are supplying the base of the subtree that the routine will search. As @ARGV will normally have no contents at all, or at least none that would be useful to you for this purpose, the @ARGV ? @ARGV : '.' almost certainly means that you are searching the subtree starting at '.', which is whatever place in the file system your CGI script is being invoked from.

Your ../cgi-bin/ directory perhaps? This would explain why you are getting the same numbers back each time. To correct this, you need to supply the upload directory directly to the find() function.



use File::Find;
my $total_size = 0;
find(sub { $total_size += -s }, $upload_dir );

I thought you might find this interesting and helpful towards solfing my problem.
The above retures a result of 5,886 which is better that the 55,000 but is still not the correct value(in my case 1760 bytes).
Does this give you any further ideas?

Bob
See they pointed out a mistake of mine, I dunno why it would work for me and not for you though.  However I did run my program in the cgi-bin, and got the directory size of one of the directorys in that folder.  So that could be why.  
So now your getting 5,886, any file's in your directory that size?  The best thing to do is make a seperate script just for testing out this filesize issue, and test that.  Make sure your path is correct, I would create a folder in the cgi-bin...call it test and just throw some files in it.  Then set $upload_dir = "test";  This should get the size of that folder.  If you can do that successfully you then just need get your script to point to the directory with the email address folders.  Thats just what I would do, if that don't work I'd go back to Perlmonks and here and let us know what's going on.  I have a feeling your really close...now that your finally getting a different size, I bet you just don't know what folder its pointing to.  I hope I've been of some help!  Good Luck

bW  

Author

Commented:
Getting closer:

As I stated above the code results in a value of 5856. However I just discovered if I remove the + sign from the += I get the value of the last file uploaded.

use File::Find;
my $total_size = 0;
find(sub { $total_size = -s }, $upload_dir );

For example I upload 4 files of 441, 441, 439, 439 bytes. The result without the + is 439 bytes.

Can you shed any light on this???

Bob

Author

Commented:
Hi,

The analyst at Perl Monks had me change the line as listed belo to see what we wer looking at.

find(sub { print STDOUT $_, -s, $/; $total_size = -s }, $upload_dir );

The result is listed below:

.4096 BandWPainting1.htm441 BandWPainting2.htm441 ColorPainting1.htm439 ColorPainting2.htm439

The 441 + 441 + 439 + 439 = 1760, the value I want.
The 4096 + 1760 = 5856, the erroneous value.

What is the '.', is it the hidden directory? If so how to I omit it besiges the bad way of hard code subtracting it?

Thanks,

Bob

Author

Commented:
The Final Result:

. represents the current directory. The size of the directory is usually a fixed amount, on your system its 4096 bytes. To fix your problem, substitute this line.Thus the 4096 + 1760 was the 5856 I was getting.

find(sub { $total_size += -s if -f }, $upload_dir );

The above line got the correct result.

Another related question. Now that the total works, I wanted to move the routine to the top before uploading the firest of the 4 potential file uploads.

If I move it, just cut and paste, I get an internal server error.

Doew it have to be after all the use CGI stuff is done.  I would like to check it each time(total of 5, before each of the 4 files and before exiting.

Also if I change the 'You've exceeded...' message from print to die to stop further processing, the screen goes blank.  Should the 'die be after the print?

Bob

Script Follows:
#!/usr/bin/perl -w
use CGI;

@valid = ('theartistloft.com');
$maxfoldersize = "200000";
$query = new CGI;

$comments = $query->param("Comments");
$filename = $query->param("file_name");  
$fsize = -s $filename;
$email_address = $query->param("email_address");

#! try to create directory
$upload_dir = "/home/bsexton/public_html/NEWClients/$email_address";
unless (-d "$upload_dir"){
mkdir ("$upload_dir", 0777);
chmod(0777, "$upload_dir");
}
#! end of create directory

$filename =~ s/.*[\/\\](.*)/$1/;

$upload_filehandle = $query->upload("file_name");

open UPLOADFILE, ">$upload_dir/$filename";
  while ( <$upload_filehandle> )
{
   
print UPLOADFILE;

}

close UPLOADFILE;

$filename1 = $query->param("file_name1");  
$fsize1 = -s $filename1;
$filename1 =~ s/.*[\/\\](.*)/$1/;


#! End of Folder Check

$upload_filehandle = $query->upload("file_name1");

open UPLOADFILE, ">$upload_dir/$filename1";
  while ( <$upload_filehandle> )
{
   
print UPLOADFILE;

}

close UPLOADFILE;

$filename2 = $query->param("file_name2");  
$fsize2 = -s $filename2;
$filename2 =~ s/.*[\/\\](.*)/$1/;


$upload_filehandle = $query->upload("file_name2");

open UPLOADFILE, ">$upload_dir/$filename2";
  while ( <$upload_filehandle> )
{
   
print UPLOADFILE;

}

close UPLOADFILE;

$filename3 = $query->param("file_name3");  
$fsize3 = -s $filename3;
$filename3 =~ s/.*[\/\\](.*)/$1/;

$upload_filehandle = $query->upload("file_name3");

open UPLOADFILE, ">$upload_dir/$filename3";
  while ( <$upload_filehandle> )
{
   
print UPLOADFILE;

}

close UPLOADFILE;

$todays_upload = $fsize + $fsize1 + $fsize2 + $fsize3;

print $query->header ( );

#! Check Folder Size

use File::Find;

my $total_size = 0;
find(sub { $total_size += -s if -f }, $upload_dir );
#!find(sub { print STDOUT $_, -s, $/; $total_size = -s }, $upload_dir );
if ($total_size > $maxfoldersize) {
print"You have exceded your limit of $maxfoldersize KB for the directory
$email_address \n";
}

#! End of Folder Check

$from = 'sales@theartistloft.com';
$subject = 'New Artist Loft Signup';

open(MAIL, "|/usr/sbin/sendmail -t");
print MAIL "To: $email_address\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
print MAIL "Dear Client:\n\n";
print MAIL "Thank you for signing up for The Artist Loft.\n\n";
print MAIL "This message is to confirm your transmission of $filename, $filename1, $filename2, $filename3 from your PC today.\n\n";
print MAIL "Your Comments: $comments\n\n";
print MAIL "For future upload modifications and use of the chatroom, please use the following information.\n\n";
print MAIL "Username = The Artist Loft\n";
print MAIL "Password = demo\n\n";
print MAIL "REMEMBER: username and password are case sensitive\n\n";
print MAIL "Thank you.\n";
print MAIL "Sales Department\n";
print MAIL "The Artist Loft\n";
close(MAIL);

$to = 'newclient@theartistloft.com';
$from = 'sales@theartistloft.com';
$subject = 'A New Artist Loft Cleint';

open(MAIL, "|/usr/sbin/sendmail -t");
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
print MAIL "Dear Sales Department:\n\n";
print MAIL "This message is to confirm transmission of $filename($fsize), $filename1($fsize1), $filename2($fsize2), $filename3($fsize3) from our new client $email_address today. Todays total was $todays_upload bytes.\n\n";
print MAIL "Client Comments: $comments\n\n";
print MAIL "The Artist Loft\n\n";
print MAIL "Size of Directory $upload_dir = $total_size\n";
close(MAIL);

print <<END_HTML;

<HTML>
<HEAD>
<TITLE>Thanks!</TITLE>
</HEAD>

<BODY>

<P align="center">&nbsp;</P>

<P align="center"><b><font size="5">Thanks for uploading your file!</font></b></P>
<P align="center"><b><font size="4">Your email address: $email_address</font></b></P>
<P align="center"><b><font size="4">Your file(s): $filename, $filename1, $filename2, $filename3</font></b></P>


</BODY>
</HTML>
END_HTML
Hey Bob glad to hear you found what you were looking for.  I new it had something to do with the current directory, and which file Perl was getting the size of.  To use your function multiple times make sure you put use File::Find; at the top of the program.  Thant could be why you were getting an error.  As far as die is concerned its normally done: die "text here";  I dunno why you would get a blank page.

2 ways you could use die:

if ($total_size > $maxfoldersize) {}
else {
    die "You have exceded your alotted file size";
}

$total_size > $maxfoldersize or die "You have exceded your limit!";

This way you don't need an if statement, all a matter of choice.  Let me know if any problems persist.

bW

Author

Commented:
One more quick question.

I moved the File::FInd and that worked out fine. So did the 'die'.

Something odd happens when checking the script.  Here is the beginning of the Code.

#!/usr/bin/perl -w
use CGI;
use File::Find;
@valid = ('theartistloft.com');
$maxfoldersize = 200000;
$query = new CGI;

$comments = $query->param("Comments");
$filename = $query->param("file_name");  
$fsize = -s $filename;

$email_address = $query->param("email_address");

#! try to create directory
$upload_dir = "/home/bsexton/public_html/NEWClients/$email_address";
unless (-d "$upload_dir"){
mkdir ("$upload_dir", 0777);
chmod(0777, "$upload_dir");
}
#! end of create directory

$filename =~ s/.*[\/\\](.*)/$1/;

#! Check Folder Size File 1

my $total_size = 0;
find(sub { $total_size += -s if -f }, $upload_dir );
#!find(sub { print STDOUT $_, -s, $/; $total_size = -s }, $upload_dir );
if ($total_size + $fsize > $maxfoldersize) {
die"You have exceded your limit of $maxfoldersize KB for the directory
$email_address \n";
}

#! End of Folder Check

Notice $maxfoldersize = 200000; for a 200KB limit.

If I run it like that it's okay. If I reduce the value say = 440; ( I was doing this to check the individual files, and my first tet file was 441 bytes, I get an Internal Server error, until I put the value to something 4 digits or more.

In other words 9999 works, but 999 gets the error. Am I using the wrog type of variable? Should numbers not be a scalar $xxxxxx variable?
Good Afternoon,

Ok, I'm not sure exactly what the problem is.  The size you are testing against is in bytes.  So to limit a $maxfoldersize to 200KB you would use 1024 * 200 = 204800 to be more precise...I dunno if that could be causing any problems for your testing, just thought I'd point it out.

The reason you may be getting a server error is each file must be at least a minimum size...depending on your harddrives' limitations.  For my system here I created a small test file, that is only 7 bytes but must take up 512 bytes on disk.  So if your testing 441 bytes, thats an imposibility on my machine and probably on yours.  Hope that helps!

bW

Author

Commented:
This is the same code as above but I posted it for your convenience.

#! Check Folder Size File 1

my $total_size = 0;
find(sub { $total_size += -s if -f }, $upload_dir );

if $total_size + $fsize > $maxfoldersize {
die"You have exceded your limit of $maxfoldersize KB for the directory
$email_address\n";
}

#! End of Folder Check

Script works until you try to exceed limit and thus fal into the 'if' statement.  Then I get the Internal Server error, and the following 2 error lines in the error log.

[Mon Nov 25 21:14:02 2002] [error] [client 24.62.132.107] File does not exist: /home/bsexton/public_html/500.shtml
[Mon Nov 25 21:14:02 2002] [error] [client 24.62.132.107] Premature end of script headers: /home/bsexton/public_html/cgi-bin/Upload.cgi


Is ther a syntax error I'm missing or what?

Thanks,

Bob
I don't really see anything wrong, 500 HTTP Error usually means there's a problem either with the shebang or with a variable/syntax.  And since you only get it when you it the if statement, I'm not seeing anything wrong.  Other than the fact that you should have parethesis around the argument.  ex: if($total_size...) {

Also you could try replacing that if statement with:
$total_size += fsize;
($total_size > $maxfoldersize) or die "You have exceded your limit of $maxfoldersize KB for the directory $email_address\n";

Both of these should really work.  But if your still having this problem...print out the variables $total_size, $fsize, $maxfoldersize and just make sure they are valid and what they are supposed to be.

bW

Author

Commented:
Hello again bW,

Most of my script seems to be working, except when I check the size and it has been exceeded. See Code Below:

#! Check Folder Size File 1

my $total_size = 0;
find(sub { $total_size += -s if -f }, $upload_dir );
my $size=$total_size+$fsize;
if ($size > $max)
{
die"You have exceeded your limit of $max for the directory $email_address\n";
}
#! End of Folder Check File 1

As soon as the $size exceeds $max I get an Internal Server error. The person at Perl Monks siad that was normal that 'die' is only for writing errors to the log file etc.

Can you think of an alternative.  All I want to do is issue a message and exit the script if the size is exceeded.

Thanks,

Bob Sexton
ok the other way to exit a program besides die is to use exit().

So you'll want to do this:

if ($size > $max) {
print "You have exceeded your limit of $max for the directory $email_address\n";
exit 0;
}

Note:  I've also seen it exit() and exit(1), I dunno what the difference is to be honest.

Hope that helps!

bW

Author

Commented:
Good Morning bW,

Kelly,

I corrected the exit problem by using exit(). I would like to check to see if the file already exists, that is to allow overwriting. Everything else is finally working.Would this just be a nested if clause and what would be the syntax.
Thanks!

#! Check Folder Size File 1

my $total_size = 0;
find(sub { $total_size += -s if -f }, $upload_dir );
my $size=$total_size+$fsize;
if ($size > $max)
{
print "Content-type: text/html\n\n";
print "<h1>Sorry,</h1><p>\n";
print "<h1>You have exceeded the limit for the directory.</h1><p>\n";
print "<h1>You may overwrite existing files, but not add new ones.Use your back button on your browser to return to the upload area.</h1><p>\n";
exit();
}
#! End of Folder Check File 1
Hey Bob,

You basically want to use -e the file test operator for existance. Your right about the nexted if clause, below is my suggested code:

if ($size > $max) {
   if (-e $filename) {
      open UPLOADFILE, ">$upload_dir/$filename";
         while ( <UPLOADFILE> )
      {
      print UPLOADFILE;
      }
   print "Content-type: text/html\n\n";
   print "You have overwritten the file $filename\n";
   exit();
   }
} else {
   print "Content-type: text/html\n\n";
   print "<h1>Sorry,</h1><p>\n";
   print "<h1>You have exceeded the limit for the directory.</h1><p>\n";
   print "<h1>You may overwrite existing files, but not add new ones.Use your back button on your browser to return to the upload area.</h1><p>\n";
   exit();
}

bW

Author

Commented:
Hey bW,

Can you see wher my logic ig wrong. It allows me to upload a file that causes the limit to be exceeded the first time.  Try to upload it again and it gets the exceeded message..

#! Check Folder Size File 4

my $total_size = 0;
find(sub { $total_size += -s if -f }, $upload_dir );
my $size=$total_size+$fsize3;
$testfile = "/home/bsexton/public_html/NEWClients/$email_address/$filename3";
if (-e $testfile){
$size=$size-$fize3;
}
if(-e $testfile) {
 
if ($size > $max)
{
print "Content-type: text/html\n\n";
print "<h1>Precheck: $size,$max</h1><p>\n";
print "<h1>Sorry,</h1><p>\n";
print "<h1>You have exceeded the limit for the directory.</h1><p>\n";
print "<h1>You may overwrite existing files, but not add new ones.Use your back button on your browser to return to the upload area.</h1><p>\n";
exit();
}
}
#! End of Folder Check File 4

#! Now upload File 4

$upload_filehandle = $query->upload("file_name3");

open UPLOADFILE, ">$upload_dir/$filename3";
  while ( <$upload_filehandle> )
{
   
print UPLOADFILE;

}

close UPLOADFILE;

#! End of upload File 4
This line: $size=$size-$fize3;
I think it should be $fsize3 not fize3;

I also don't understand why you do two tests on the $filesize:

if (-e $testfile){
$size=$size-$fsize3;
}
if(-e $testfile) {

you should just bring the $size=$size-$fize3; down into the second if statement and delete the first...just a matter of style really.

I don't know exactly what the solution is, but it looks to me like you could have an error in your size calculations.  I don't really follow your logic here.  You set size equal to total_size plus file3 then later you say size=size-file3.  Your program before u checked for exsistence didn't allow for sizes bigger than max size did it?  If not then your probably just calculating the size a little wierd, use print statements and replicate your problem to figure out where the problem is.  Let me know if u can narrow it down any further.

bW

Commented:
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

Accept a comment by Willman023

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

inq123
EE Cleanup Volunteer

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial