testing if uploaded file is < 300kb

hello,
I need to validate a uploaded file, The max file size can only be 300 kb or less,
Im close, but im getting an error, this is my error...

Warning: filesize(): Stat failed for julie.jpg (errno=2 - No such file or directory) in /u/j/jeremy/www.website.com/admin/upload.php on line 29

this is my script, the validation starts here at this line ($maxfilesize=307200;)

error_reporting (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

$uploadDir = "/u/j/jeremy/www.website.com/admin/uploads/";
$fileName = $_FILES['file']['tmp_name'];
$userfileName = str_replace(" ","_",$_FILES['file']['name']);

$maxfilesize=307200;
$fileName = fileName($userfileName);
if ($fileName > $maxfilesize)
header("Location: uploadImage.php");
else

move_uploaded_file($fileName, $uploadDir. $userfileName);
$source = imagecreatefromjpeg($uploadDir. $userfileName);
$dest = imagecreate(100, 100);

$system=explode(".",$userfileName);
if (preg_match("/jpg|jpeg/",$system[1])){
$src_img=imagecreatefromjpeg($uploadDir. $userfileName);
}
if (preg_match("/png/",$system[1])){
$src_img=imagecreatefrompng($uploadDir. $userfileName);
}

$original_x=imageSX($src_img);
$original_y=imageSY($src_img);
if ($original_x > $original_y) {
$thumb_w=100;
$thumb_h=$original_y*(100/$original_x);
}
if ($original_x < $original_y) {
$thumb_w=$original_x*(100/$original_y);
$thumb_h=100;
}
if ($original_x == $original_y) {
$thumb_w=100;
$thumb_h=100;
}
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$original_x,$original_y);

if (preg_match("/png/",$system[1])){
imagepng($dst_img,$uploadDir."th_".$userfileName);
} else {
imagejpeg($dst_img,$uploadDir."th_".$userfileName);
}
imagedestroy($dst_img);
imagedestroy($src_img);


LVL 1
jblayneyAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

lozlozCommented:
hi,

i assume you've mistyped this line and the function is meant to be filesize:

$fileName = fileName($userfileName);

you probably want to change it to:

$fileSize = filesize($fileName);

then the following line should be:

if ($fileSize > $maxfilesize)

another way to check file size is putting this in your form:

<input type="hidden" name="MAX_FILE_SIZE" value="307200">

loz
jblayneyAuthor Commented:
you are right about the file size, it is fileseize, i tried filename as an experiment,..

how do i use that form thing, with javascript ?, i have javascript alerst for the other form fields.
lozlozCommented:
you just simply put it in your html code inside your form

e.g.
<form>
<input type="text" name="name" value="myvalue">
<input type="hidden" name="MAX_FILE_SIZE" value="307200">
<input type="submit" name="submit" value="Submit form">
</form>

loz
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

jblayneyAuthor Commented:
your right tx
i had just tested that and it worked, unfortunatly all it did was kill the script, how can i make an alert happen if they go over the max size?
lozlozCommented:
it's probably best not to use that to check the exact size of the file but rather to limit it to a larger size so that users don't wait for a long time uploading a ridiculously large file, so maybe just have <input type="hidden" name="MAX_FILE_SIZE" value="400000">

and continue with your previous method of checking the file size. is the processing part working?

loz

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jblayneyAuthor Commented:
the php part is not working... : (
and actually i think i am scrapping the whole project, the client wanted a script that would upload a large image 1-2 megs and create a thumbnal of it. What I am finding is that anything over 300 kbs goes corrupt and also some jpgs that are under 300 kbs cause server errors (fake jpg's ????). My client will not accept that, they need 1 -2 meg files, So what i am doing now is trying to write a upload script that will upload 2 files at once, one file being 1-2 megs and the other being a thumbnail.

I will give you the points, If you know a 100% sure fire way to do what I need done, please let me know, or if u have a simple script  that will upload 2 files at once
lozlozCommented:
hi,

it's certainly possible, so just take out this max file size parsing if it's not necessary. below is an example of a script i use to accept a file, find the dimensions of it and create a thumbnail (needs gd image library for the resizing part - you also need to change the variable $mydir at the top of the script):


<?php

$mydir = "../mydir" // change this to be the folder you want to place the image + thumbnail into, in relation to your script. do not include / at the end

/* resizeToFile resizes a picture and writes it to the harddisk
*  
* $sourcefile = the filename of the picture that is going to be resized
* $dest_x   = X-Size of the target picture in pixels
* $dest_y   = Y-Size of the target picture in pixels
* $targetfile = The name under which the resized picture will be stored
* $jpegqual   = The Compression-Rate that is to be used
*/

function resizeToFile ($sourcefile, $dest_x, $dest_y, $targetfile, $jpegqual = "80")
{


/* Get the dimensions of the source picture */
$picsize=getimagesize("$sourcefile");

$source_x = $picsize[0];
$source_y  = $picsize[1];
$source_id = imageCreateFromJPEG("$sourcefile");

/* Create a new image object (not neccessarily true colour) */

$target_id=imagecreatetruecolor($dest_x, $dest_y);

/* Resize the original picture and copy it into the just created image
  object. Because of the lack of space I had to wrap the parameters to
several lines. I recommend putting them in one line in order keep your
  code clean and readable */


$target_pic=imagecopyresampled($target_id,$source_id,
                             0,0,0,0,
                              $dest_x,$dest_y,
                              $source_x,$source_y);

/* Create a jpeg with the quality of "$jpegqual" out of the
  image object "$target_pic".
  This will be saved as $targetfile */

imagejpeg ($target_id,"$targetfile",$jpegqual);

return true;

}
if($_POST["submit"]) {
  if($_FILES['image'] != "") {
    copy($_FILES['image']['tmp_name'], $mydir . "/" . $_FILES['image']['name'])
      or die("Couldn't copy the file!");  
  } else {
    die("No input file specified");
  }
  $imageinfo = getimagesize($mydir . "/" . $_FILES["image"]["name"]);
  $multiple = 150 / $imageinfo["0"];
  $height = $imageinfo["1"] * $multiple;
  $height = round($height);
  $small = explode(".", $_FILES['image']['name']);
  $preview = $small[0] . "_s." . $small[1];
  resizeToFile($mydir . "/" . $_FILES["image"]["name"], "150", $height, $mydir . "/" . $preview");
  print "<p>Image added</p>\n";
}
?>

tell me how you get on

loz
jblayneyAuthor Commented:
tx loz,
well, i copied and pasted into my document and changed what needed to be changed.. But i am getting a parse error on line 24, which is the line that the function starts. Also one of the last lines

resizeToFile($mydir . "/" . $_FILES["image"]["name"], "150", $height, $mydir . "/" . $preview");

I think should have a " before $preview, I say this because i use dreamweaver and the code colouring got all messed up their, after i added that, it was fixed..

copying nd pasting documenst through a browser always causes errors, hidden characters are added and some characters are deleted, so i am just trying to figure out what happened here.. you can email it to me at justin@justinblayney.com
lozlozCommented:
nah that was actually my fault, i was modifying my script on the spot and forgot to take out that last "

resizeToFile($mydir . "/" . $_FILES["image"]["name"], "150", $height, $mydir . "/" . $preview);

is what it should be

tell me how it goes

loz
jblayneyAuthor Commented:
ok, tx
im still getting a parse error on line 24, thats where the function starts

error_reporting (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$mydir = "../uploads"
function resizeToFile($sourcefile,$dest_x,$dest_y,$targetfile,$jpegqual="80")
{
$picsize=getimagesize("$sourcefile");
$source_x = $picsize[0];
$source_y  = $picsize[1];
$source_id = imageCreateFromJPEG("$sourcefile");
$target_id = imagecreatetruecolor($dest_x, $dest_y);
$target_pic=imagecopyresampled($target_id,$source_id,0,0,0,0,
$dest_x,$dest_y,
$source_x,$source_y);
/* Create a jpeg with the quality of "$jpegqual" out of the
image object "$target_pic".
This will be saved as $targetfile */
imagejpeg ($target_id,"$targetfile",$jpegqual);
return true;
}
if($_POST["submit"]) {
if($_FILES['image'] != "") {
copy($_FILES['image']['tmp_name'], $mydir . "/" . $_FILES['image']['name'])
or die("Couldn't copy the file!");  
} else {
die("No input file specified");
}
$imageinfo = getimagesize($mydir . "/" . $_FILES["image"]["name"]);
$multiple = 150 / $imageinfo["0"];
$height = $imageinfo["1"] * $multiple;
$height = round($height);
$small = explode(".", $_FILES['image']['name']);
$preview = $small[0] . "_s." . $small[1];
resizeToFile($mydir . "/" . $_FILES["image"]["name"], "150", $height, $mydir . "/" . $preview);
print "<p>Image added</p>\n";
}
lozlozCommented:
add a ; after the declaration:

$mydir = "../uploads";

loz
jblayneyAuthor Commented:
grrr...
lots of parse errors, i am now stuck on line 44 the "else" thats here

or die("Couldn't copy the file!");  
} else {
die("No input file specified");

i integrated this  with my sql

error_reporting (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$mydir = "../uploads";
function resizeToFile($sourcefile,$dest_x,$dest_y,$targetfile,$jpegqual="80")
{
$picsize=getimagesize("$sourcefile");
$source_x = $picsize[0];
$source_y = $picsize[1];
$source_id = imageCreateFromJPEG("$sourcefile");
$target_id = imagecreatetruecolor($dest_x, $dest_y);
$target_pic=imagecopyresampled($target_id,$source_id,0,0,0,0,
$dest_x,$dest_y,
$source_x,$source_y);
/* Create a jpeg with the quality of "$jpegqual" out of the
image object "$target_pic".
This will be saved as $targetfile */
imagejpeg ($target_id,"$targetfile",$jpegqual);
return true;
}
if($_POST["submit"]) {
if($_FILES['image'] != "") {
copy($_FILES['image']['tmp_name'], $mydir . "/" . $_FILES['image']['name'])
or die("Couldn't copy the file!");  
} else {
die("No input file specified");
}

$imageinfo = getimagesize($mydir . "/" . $_FILES["image"]["name"]);
$multiple = 150 / $imageinfo["0"];
$height = $imageinfo["1"] * $multiple;
$height = round($height);
$small = explode(".", $_FILES['image']['name']);
$preview = $small[0] . "_s." . $small[1];
resizeToFile($mydir . "/" . $_FILES["image"]["name"], "150", $height, $mydir . "/" . $preview);
print "<p>Image added</p>\n";

$db_name = "mine";
$table_name = "image_uploads";
$connection = @mysql_connect("localhost", "user", "pass") or die("Problems connecting - Try again");
$db = @mysql_select_db($db_name, $connection) or die("Problems connecting - please try later");
$sql = "INSERT INTO $table_name
(imageID, imageName, imageNameS, imageClientID, imageBlurb, imageDate)
VALUES('', '".$sourcefile."', 'th_".$userfileName."', '$id', '$imageBlurb', '$todayDate')";
$result =@mysql_query($sql, $connection) or die("Sorry, coudn't execute query - please try later");
}
jblayneyAuthor Commented:
ok, i got a new error,
i delted all he blank spaces from the "else", the error i get now is

Notice: Undefined index: submit in /u/j/jeremy/www.sirencommunications.com/admin/upload.php on line 40

line 40 is
if($_POST["submit"]) {

the form used for this is on another page, this page just processes inserts into db
lozlozCommented:
what do you mean by deleted all the blank spaces from the else? can i see all the code for the script?

loz
jblayneyAuthor Commented:
error_reporting (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$mydir = "../uploads";
function resizeToFile($sourcefile,$dest_x,$dest_y,$targetfile,$jpegqual="80")
{
$picsize=getimagesize("$sourcefile");
$source_x = $picsize[0];
$source_y = $picsize[1];
$source_id = imageCreateFromJPEG("$sourcefile");
$target_id = imagecreatetruecolor($dest_x, $dest_y);
$target_pic=imagecopyresampled($target_id,$source_id,0,0,0,0,
$dest_x,$dest_y,
$source_x,$source_y);
/* Create a jpeg with the quality of "$jpegqual" out of the
image object "$target_pic".
This will be saved as $targetfile */
imagejpeg ($target_id,"$targetfile",$jpegqual);
return true;
}
if($_POST["submit"]) {
if($_FILES['image'] != "") {
copy($_FILES['image']['tmp_name'], $mydir . "/" . $_FILES['image']['name'])
or die("Couldn't copy the file!");
}else{
die("No input file specified");
}

$imageinfo = getimagesize($mydir . "/" . $_FILES["image"]["name"]);
$multiple = 150 / $imageinfo["0"];
$height = $imageinfo["1"] * $multiple;
$height = round($height);
$small = explode(".", $_FILES['image']['name']);
$preview = $small[0] . "_s." . $small[1];
resizeToFile($mydir . "/" . $_FILES["image"]["name"], "150", $height, $mydir . "/" . $preview);
print "<p>Image added</p>\n";

$db_name = "mine";
$table_name = "image_uploads";
$connection = @mysql_connect("localhost", "user", "pass") or die("Problems connecting - Try again");
$db = @mysql_select_db($db_name, $connection) or die("Problems connecting - please try later");
$sql = "INSERT INTO $table_name
(imageID, imageName, imageNameS, imageClientID, imageBlurb, imageDate)
VALUES('', '".$sourcefile."', 'th_".$userfileName."', '$id', '$imageBlurb', '$todayDate')";
$result =@mysql_query($sql, $connection) or die("Sorry, coudn't execute query - please try later");
}
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.