Jump to content

for loop messing up image upload


ball420

Recommended Posts

what I'm doing is uploading multiple images, usually a different amount each time. That works fine until I added a for loop using the rename function to get the images just uploaded and rename them. What's happening now is only the last image in the $uploaded_files array is actually being uploaded and being renamed. Am i using the wrong syntax somewhere? Thanks in advance for the replies.

 

 

 

 

 

 

if (isset($_POST['Submit'])) {

    $number_of_file_fields = 0;
    $number_of_uploaded_files = 0;
    $number_of_moved_files = 0;

$unique_Id = uniqid();

    $uploaded_files = array();
$upload_directory = dirname(__file__) . '/car-images/'; //set upload directory
    /**
     * we get a $_FILES['images'] array ,
     * we procee this array while iterating with simple for loop 
     * you can check this array by print_r($_FILES['images']); 
     */
    for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
        $number_of_file_fields++;
        if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not
            $number_of_uploaded_files++;
            $uploaded_files[] = $_FILES['images']['name'][$i];
            if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . $_FILES['images']['name'][$i])) {

                $number_of_moved_files++;
			 }

        }

    }

///This is the loop that's making it only upload one image and rename it. 	
for ($i=0; $i < $number_of_uploaded_files; $i++)
  {	
  
  rename($upload_directory . $uploaded_files[$i], $upload_directory . $unique_Id . '.jpg');

  }

Link to comment
https://forums.phpfreaks.com/topic/254861-for-loop-messing-up-image-upload/
Share on other sites

Do the renaming in the first for loop, and get rid of that second loop

 

It's just as easy to add a timestamp to the front of the image name

if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . time()."-".$_FILES['images']['name'][$i])) {

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.