INOH INOH - 25 days ago 9
PHP Question

echo message that all files have been uploaded

I am uploading multiple file to folder using PHP. after uploading has been completed i am getting browser message for each file uploaded. My question is how can I just have message for all when completed and if there was an error just show which files did not upload. here is my script below, and thanks in advance

<?php

// Count # of uploaded files in array
$total = count($_FILES['filesToUpload']['name']);

// Loop through each file
for ($i = 0; $i < $total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['filesToUpload']['tmp_name'][$i];

//Make sure we have a filepath
if ($tmpFilePath != "") {
//Setup our new file path
$newFilePath = "./upimages/" . $_FILES['filesToUpload']['name'][$i];

//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
?><script>alert('successfully uploaded');</script><?php
} else {
?><script>alert('error while uploading file');</script><?php
}
}
}
?>

Answer

Just make a simple variable $error and $succes. You can display those after the matter (when your loop ends). I have now printed every error and succes seperatly, you can do whatever you want with those arrays.

<?php

$total = count($_FILES['filesToUpload']['name']);
$succes = [];
$error = [];
for($i=0; $i<$total; $i++) {
    $tmpFilePath = $_FILES['filesToUpload']['tmp_name'][$i];
    if ($tmpFilePath != ""){
    $newFilePath = "./upimages/" . $_FILES['filesToUpload']['name'][$i];
        if(move_uploaded_file($tmpFilePath, $newFilePath)) {
            $succes[$_FILES['filesToUpload']['name'][$i]] = true;
        }else{
            $errors[$_FILES['filesToUpload']['name'][$i]] = true;
        } 
    }
}
foreach(array_keys($succes) as $suc){
    echo $suc." was succesfull";
}
foreach(array_keys($errors) as $error){
    echo $error." failed to upload";
}

?>