Dejavu Dejavu - 4 months ago 11
PHP Question

Upload multiple files and return file info as object

I am trying to create a simple uploader class to use uploading multiple images. I need to return file info from uploadFiles method and use it inside another method (uploadGalleryImages). However if I use return $result then foreach loop stops after first file is uploaded. If I don't return it and just use print_r($result) I can upload all files and see the object in chrome's network tab. Here is my simplified code:

public function uploadGalleryImages() {
$upload_image = $this->uploadFiles($_FILES['image']);
}

private function reArrayFiles($files) {
$array = array();
$file_count = count($files['name']);
$file_keys = array_keys($files);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$array[$i][$key] = $files[$key][$i];
}
}
return $array;
}


private function uploadFiles($files = array()) {
$upload_dir = IMAGE_UPLOAD_DIR;
$thumb_dir = $upload_dir . 'thumbnails/';

$file_array = $this->reArrayFiles($files);

foreach ($file_array as $file) {

$base_name = pathinfo($file['name'], PATHINFO_FILENAME);
$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

$counter = 1;
while(file_exists($upload_dir . $file['name'])) {
$file['name'] = $base_name . $counter . '.' . $extension;
$counter++;
};

if (move_uploaded_file($file['tmp_name'], $upload_dir . $file['name'])) {
$result = new \stdClass();
$result->file_name = $file['name'];
$result->extension = $extension;
//print_r($result);
return $result; // Stops after first file uploaded
} else {
return false;
}

}
}

Answer

Store all picture objects in array and return it. Simple example:

$pics = [];
foreach ($file_array as $file) {

    if (move_uploaded_file($file['tmp_name'], $upload_dir . $file['name'])) {
        $result = new \stdClass();
        $result->file_name = $file['name'];
        $result->extension = $extension;
        $pics[] = $result;
    } 
}

return $pics;