Solved

testing if uploaded file is  < 300kb

Posted on 2003-12-01
15
291 Views
Last Modified: 2008-02-01
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);


0
Comment
Question by:jblayney
  • 8
  • 7
15 Comments
 
LVL 13

Expert Comment

by:lozloz
ID: 9850529
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
0
 
LVL 1

Author Comment

by:jblayney
ID: 9850585
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.
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9850613
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
0
Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 1

Author Comment

by:jblayney
ID: 9850634
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?
0
 
LVL 13

Accepted Solution

by:
lozloz earned 25 total points
ID: 9850738
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
0
 
LVL 1

Author Comment

by:jblayney
ID: 9851331
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
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9851412
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
0
 
LVL 1

Author Comment

by:jblayney
ID: 9851618
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
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9851940
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
0
 
LVL 1

Author Comment

by:jblayney
ID: 9852562
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";
}
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9852685
add a ; after the declaration:

$mydir = "../uploads";

loz
0
 
LVL 1

Author Comment

by:jblayney
ID: 9853046
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");
}
0
 
LVL 1

Author Comment

by:jblayney
ID: 9853352
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
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9853386
what do you mean by deleted all the blank spaces from the else? can i see all the code for the script?

loz
0
 
LVL 1

Author Comment

by:jblayney
ID: 9853481
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");
}
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
does post require a form or curl to be post 4 55
Why is my wamp get_include_path() wrong? 2 21
how to access a remote mysql database with xampp 3 23
Help with PHP 13 27
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question