Skip to content
Advertisement

PHP Upload Multiple Images through Loop

I am trying to upload multiple images in a loop but for some reason it will create the directory, upload 1 file and create the MySQL record so I’m not sure why it only uploads 1 file even though when i’ve printed $i to see how many files have been counted it always counts the correct amount.

PHP

JavaScript

HTML

JavaScript

I’ve uploaded the HTML form and the PHP script that is run when the form is submitted, as far as I’m aware my script will check if the form has been submitted, generate a random string which becomes the new directory name which after i’ve checked if it’s been created or not then if not the new directory is created and then i run a loop to loop through and upload all selected images to that directory and finally I upload the data to the MySQL table.

Advertisement

Answer

The problem, I believe having gone through the code properly and tested it lies with the fact that the files are being saved with a new name and that new name is generated using:

JavaScript

When I tested this on a 3 file upload I observed the following when I added some debug statements.

JavaScript

All three were assigned the same name and thus only the last appears to be uploaded as the other two were overwritten.

The debug mentioned was:

JavaScript

One would assume that the $errorTxt here would state the file already exists but it does not because $target_file and $newfilename will not be the same. The new name should be generated before the if (file_exists($target_file)) { check.

So – if you change the relevant code in your original to this the logic test will work but the files will still fail to upload.

JavaScript

The issue now is that $newfilename = round( microtime(true) ) will generate the same integer – a large integer but the same. The precision derived from the microtime is lost so you could modify that to:

JavaScript

With that done all should be well with your code – three images uploaded OK.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement