Jump to content

Problems adding multiple upload fields to upload script


perky416

Recommended Posts

Hi everyone,

 

I have a page that i use to upload images to my website, i got a bit fed up of uploading one at a time so i decided to add multiple file fields to the form to upload multiple images at the same time.

 

Im having a few problems, iv read up here: http://www.php.net/manual/en/features.file-upload.multiple.php and it seems all i have to do is add [] to the form names to turn them into arrays. However when i come to upload the images, i keep getting the "$error[] = "Incorrect format!...." error from the code below. I cant seem to figure out what the problem is.

 

Could anybody please point me in the right direction?

 

<?php 
session_start();

$id = $_SESSION['id'];

$connect = mysql_connect("localhost","leemp5_admin","p7031521");
mysql_select_db("leemp5_database");

$query = mysql_query("SELECT * FROM users WHERE id='$id'");
$row = mysql_fetch_assoc($query);

$username = $row['username'];

$submit = $_POST['submit'];

$type = $_FILES['image']['type'];
$size = $_FILES['image']['size'];
$max_size = "1000"; 
$width = "100"; 
$height = "100";

$error = array();

function make_thumb($image_name,$filename,$new_width,$new_height) 
{
$ext=getExtension($image_name); 

if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) 
$source_image=imagecreatefromjpeg($image_name);   

if(!strcmp("png",$ext)) 
$source_image=imagecreatefrompng($image_name);

if(!strcmp("gif",$ext)) 
$source_image=imagecreatefromgif($image_name); 

$old_x=imageSX($source_image);
$old_y=imageSY($source_image);   

$ratio1=$old_x/$new_width; 
$ratio2=$old_y/$new_height; 

if($ratio1>$ratio2)
{ 
	$thumb_width=$new_width; 
	$thumb_height=$old_y/$ratio1; 
} 
else 
{ 
	$thumb_height=$new_height;
	$thumb_width=$old_x/$ratio2; 
} 
  
$destination_image=ImageCreateTrueColor($thumb_width,$thumb_height);   

imagecopyresampled($destination_image,$source_image,0,0,0,0,$thumb_width,$thumb_height,$old_x,$old_y);   

if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
{
	imagejpeg($destination_image,$filename); 
}

if(!strcmp("png",$ext)) 
{
	imagepng($destination_image,$filename); 
}

if(!strcmp("gif",$ext)) 
{
	imagegif($destination_image,$filename); 
}

imagedestroy($destination_image); 
imagedestroy($source_image); 
}   


function getExtension($str)
{ 
$i = strrpos($str,"."); 
if (!$i) { return ""; } 
$l = strlen($str) - $i; 
$ext = substr($str,$i+1,$l); 
return $ext; 
}   

if($submit) 
{ 
$image=$_FILES['image']['name']; 

if ($image) 
{ 
	$filename = stripslashes($_FILES['image']['name']);   
	$extension = getExtension($filename); 
	$extension = strtolower($extension); 

	if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
	{ 
		$error[] = "Incorrect format! Please make sure your image is a .jpg, .jpeg, .png or .gif file.";
	} 
	else
	{ 
		$size=getimagesize($_FILES['image']['tmp_name']); 
		$sizekb=filesize($_FILES['image']['tmp_name']); 
  
		if ($sizekb > $max_size*1024) 
		{ 
			$error[] = "Your image is too big! The maximum upload size is 1MB.";
		}   
		else
		{
			$image_name=time().'.'.$extension; 

			$newname="uploads/" . $username . "/images/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); 

			if (!$copied) 
			{ 
				$error[] = "There was an error uploading your image. Please try again!";
			} 
			else 
			{ 
				$thumb_name='uploads/' . $username . '/images/thumbs/thumb_'.$image_name; 
					$thumb=make_thumb($newname,$thumb_name,$width,$height); 
			}
		}
	}
}
else
{
	$error[] = "Please select an image to upload!";
}

if(empty($error))
{
	echo "Upload Successfully!<br />"; 
	echo '<img src="'.$thumb_name.'">';
	mysql_query("INSERT INTO images VALUES ('','$username','$image_name','','','','','uploads/$username/images/$image_name','uploads/$username/images/thumbs/thumb_$image_name','$type','$size')");
}
else
{
    	echo implode($error);
}
}
?>
<form method="post" enctype="multipart/form-data" action="upload_images.php">
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="submit" name="submit" value="Upload">
</form>

 

Thanks

Link to comment
Share on other sites

Write a mickey-mouse test program and print out POST variables and FILES variables. Then you will understand what you are doing wrong. Basically we need a very small example we dont need a large chunk of your program.

 

Maybe try something like this very basic test code. Obviously I have not tried it, but you probably get the idea. Start with basic stuff, and then add your real code into these working test lines. That is what I do anyway.

 

<?php 
var_dump($_FILES);
var_dump($_POST);
// so that you can see what is going on...
?>

<form method="post" enctype="multipart/form-data" action="">
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="submit" name="submit" value="Upload">
</form>

Link to comment
Share on other sites

Hi,

Thanks for your suggestion, iv just tried the var_dump method but i didn't know how to make heads or tails of the output.

Iv been playing with the script, i deleted the code that gives the incorrect format error message and now when i try to upload im presented with the following errors:

 

Warning: getimagesize(Array) [function.getimagesize]: failed to open stream: No such file or directory in /home/user/public_html/website.co.uk/upload_images.php on line 103

 

Warning: filesize() [function.filesize]: stat failed for Array in /home/user/public_html/website.co.uk/upload_images.php on line 104

 

Warning: copy(Array) [function.copy]: failed to open stream: No such file or directory in /home/user/public_html/website.co.uk/upload_images.php on line 114

There was an error uploading your image. Please try again!

 

It looks like the problem may be with "$_FILES['image']" as i have that on lines 103, 104 and 114. The incorrect format error also leads back to "$_FILES['image']" through a number of variables. Image is also the name of the form inputs.

 

Does anybody have any ideas as google keeps leading me blank?

 

Thanks

Link to comment
Share on other sites

Your code has absolutely NO error checking logic in it to test if the upload worked before blindly attempting to use any of the uploaded file information. See Example #3 at this link - http://us.php.net/manual/en/features.file-upload.post-method.php for some php code that will loop though the uploaded files and ONLY process them if they were successfully uploaded (no upload errors.)

Link to comment
Share on other sites

Hi PFMaBiSmAd,

 

Please could you elaborate as im new to php. Is what you are referring to specifically for arrays or just my code in general?

 

I thought where iv put the $error[] = was the checking for errors. I was under the impression that first it checks the file extension, if it is none of those specified it displays an error, else if the extension is ok it moves on to check file size, if the file size is bigger than that specified it displays an error, else it goes on to move the file from he temp directory to the specified location on my server.

 

Im all confused now lol.

Link to comment
Share on other sites

Your code that is checking the extension is validating information about the uploaded file(s). You cannot (successfully) do that until you know the file has been uploaded without error (there are a few of the possible upload errors that will populate the uploaded file name, but there is no uploaded file.)

 

In order for you to iterate over the array of uploaded files, you must use array functions to do that. The link I posted above does what you need. Your php code won't work until you change it to iterate over the array it receives, which is why you were getting your "Incorrect format!...." error message. Removing the logic that was producing that error message, didn't fix anything, it just removed code that was pointing out where a problem was occurring at.

Link to comment
Share on other sites

Thank you, i think i understand what your saying a bit better. I tried using the code on the link you gave me however im still getting the original 3 warning messages. Would it be easier for me to give each upload field an individual name rather than use an array?

 

Thanks

Link to comment
Share on other sites

No! It would be counterproductive to assign each form a specific name.

What PFMaBiSmAd wants you to do before your script starts uploading the file, is check the file for possible errors.

$_FILES is a superglobal, when an upload is processed it's information is stored in $_FILES as an array, that array has the temporary folder location, and possible errors that could have happened with your script.

 

Your script currently checks if there was a file name assigned, so even incorrect files, say files that are over your set size limit can bypass this, as you don't check if the file is too big, or if it successfully obtained a temp file.

 

So you need to do some checks, http://www.php.net/manual/en/features.file-upload.errors.php is a good resource to what errors are set to the error key.

 

What I recommend doing is first having your script check and see if the form has been processed.

 

<?php
if (isset($_POST['submit']))
{
   $file_errors = 0;
   foreach ($_FILES AS $file)
   {
       if ($file['error'] == 'UPLOAD_ERR_PARTIAL')
       {
            $file_errors++;
            $errors[] = 'file was partially uploaded';
       }
       else if ( $file['error'] 'SO_ON')
       {
           $file_errors++;
           $errors[] = '';
       }
   }
   //  this means that no errors came from your uploaded files, so we can proceed with customer checks
   if ($file_errors == 0)
   { 
     // you can do your necessary checks, fo file types, things like that
      if ($type != 'jpg')
      {
      }
      // continue the script after your other necessary checks.
   }
}
?>

 

this is just a basic example of how you need to check and see if any errors came from $_FILES, if that passes you can do custom error checks and proceed with the upload.

After you've fixed this, let me know what error you get stuck at.

 

Link to comment
Share on other sites

It seems that a php book or training course is in order.

 

Really, most people would like to answer a quick question about what is going wrong with code posted to the forum, not individual programming problems related to individual cases. That way we can spread ourselves out among the problems better.

 

Ideally, we need you to extract the problem you are having, place it in a test program, and try it out yourself. Then if it still does not work, post the few lines of code which are causing problems so that we can help you.

 

I guess you wont like what I have said, but place yourself in our position.

Learning programming is not done overnight from forums unfortunately otherwise everyone would be doing it.

Link to comment
Share on other sites

creata.physics thank you that is much clearer i get it now. After reading through your post, and then back through PFMaBiSmAd's post it makes much more sense. Maybe my brain was tires last night after been at it all night lol.

 

opaul20, what can i say im an engineer lol. When i started out doing web design i tried reading through books, researching on the internet but i just couldn't grasp it, the only way I eventually learned was through creating sites and then asking questions in forums when i came across a problem. I get what your saying about the exact problem, i thought it was specifically with my code thats why i was all confused but now after the recent posts and looking up on php.net i think i get what i have to do.

 

I will give it a go and try and come back with an upload error.

 

Thanks again.

Link to comment
Share on other sites

I just wanna say a massive thank you.

 

PFMaBiSmAd when i tried using the info on the link you gave me I was only using UPLOAD_ERR_OK which is why it still wasn't working.

creata.physics when you gave me the example code and your link i realised that there were a number of different upload errors. When i combined the information from the 2 links it works perfectly.

 

THANK YOU!!!

Link to comment
Share on other sites

I may have spoke too soon.

 

When i try to add my own validation after UPLOAD_ERR_OK it just doesn't want to work.

 

    	if ($error == UPLOAD_ERR_OK)
	{
		$filename = stripslashes($_FILES['image']['name']);   
		$extension = getExtension($filename); 
		$extension = strtolower($extension);

		if ($extension == "jpg")
		{
        		$tmp_name = $_FILES['image']['tmp_name'][$key];
        		$name = $_FILES['image']['name'][$key];
        		move_uploaded_file($tmp_name, "uploads/$name");
			echo "Upload Sucesfull";
		}
		else
		{ 
			echo "Incorrect Format";
		}
	}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.