...

View Full Version : Uploading multiple images?



stfc_boy
03-26-2009, 10:13 AM
I'm wondering if someone can help me convert my single image uploader to a multiple file uploader.

Basically it takes the image, renames it and uploads it to a folder on my server, with the filename of the image held in my database:



<?php
if (isset($_POST['Submit']))
{
// set the image details and upload the file
$picunique = time();
$picture = "/home/******/images/$picunique.jpg";
move_uploaded_file ($_FILES['ufile']['tmp_name'][0], $picture);

// and insert into the database
$result = mysql_query("Insert into image_test (picture) values('". basename($picture) ."')") or die(mysql_error());
$picture_id=mysql_insert_id();
$error = "Sucess - everything uploaded";
}
?>
<form action="" method="post" enctype="multipart/form-data" name="myform" id="myform">
<h3>Submit your Pic</h3>
<?php echo $error;?>
<fieldset>
<legend>Please Upload your picture below: </legend>
<p>
<label for="Main Picture">Upload Image:</label>
<input name="ufile[]" type="file" id="ufile[]" />
</p>
<input name="Submit" type="submit" value="Submit" />
<input name="Reset" type="reset" value="Reset" />
</fieldset>
</form>
</body>
</html>


Now, i've started the creation of my multiple uploader:

Here (http://www.inspireaway.co.uk/multi/multiple.php?num=10)

with ?num= being any number, and that creates how many upload fields I get on the page dynamically:



<form action="" method="post" enctype="multipart/form-data" name="myform" id="myform">
<?php
$number = $_GET['num'];
for($i = 0; $i <= $number; $i++)
{
echo "
<p>Upload Image (".$i."):<input name=\"ufile[]\" style=\"width:300px;\" type=\"file\" id=\"ufile[]\" /></p>\n";
}
?>
</form>


So i'd like to it so it re-names each image like the single uploader I created and saves the filename row, by row in the database.

Can anyone kindly advise as i'm not sure how this can be done?

Thanks

Fumigator
03-26-2009, 05:29 PM
You just need to loop your uploaded file processing code using foreach().

Here's a start (not a complete snippet):



// set the image details and upload the file
foreach ($_FILES['ufile']['name'] as $key => $val) {
$picunique = microtime();
$picture = "/home/******/images/$picunique.jpg";
move_uploaded_file ($_FILES['ufile']['tmp_name'][$key], $picture);

// and insert into the database
$result = mysql_query("Insert into image_test (picture) values('". basename($picture) ."')") or die(mysql_error());
$picture_id=mysql_insert_id();
}
//Need to actually check the errors before declaring everything a success
$error = "Sucess - everything uploaded";


You really should add some error checking in there as well so you can report back to the user when and if something goes wrong with the upload process. (Errors are stored in $_FILES['ufile']['error'][$key])

(Note I used microtime() rather than time() as you'll probably process all files in less than a second)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum