Jagr
Jagr

Reputation: 502

PHP Loop through nested directories

In my code i created a folder and sub folders for that directory. So when a user sends files, I create a directory with their "userid_fullname",loop through the files, and submit to fullname folder. But every time a user submits files, the first one would go to the folder and others would disappear. I believe the problem is this my "$key" variable because it controls the count. Here is my code.

PHP

<?php

if($_SERVER['REQUEST_METHOD'] =="POST"){
    $currentDirectory = getcwd();

    $userid = "8503";
    $fullname = "peopl39e";    


    foreach($_FILES['file']['tmp_name'] as $key => $error){

        $file_tmp = file_get_contents($_FILES['file']['tmp_name'][$key]);
         //keep only A-Z and 0-9 and everything else KILL
        $file_name = preg_replace("/[^a-z0-9\.]/", "_", strtolower($_FILES['file']['name'][$key]));
        $file_name = strtotime("now")."_".$file_name;

        $dir = "devPacks/" .$userid."_".$fullname;
        if(is_dir($dir)==false){

                mkdir($dir, 0777);
            }
        if(!move_uploaded_file($_FILES['file']['tmp_name'][$key],$dir.'/'.$file_name)){

                die("File didn't send!");

    }else{


            die("GOOD");
        }
}
}

?>

<form method="post" enctype="multipart/form-data" autocomplete="off">
    <br>
    Select Pack Screenshots/Video: <input type="file" name="file[]" multiple>
<br></br>
    <input type="submit" name="submit">
</form>

Upvotes: 1

Views: 81

Answers (1)

Kamrul Khan
Kamrul Khan

Reputation: 3350

The following portion of your code will stop execution after the loop runs once:

 if(!move_uploaded_file($_FILES['file']['tmp_name'][$key],$dir.'/'.$file_name)){

            die("File didn't send!");

}else{


        die("GOOD");
    }
}

If I understand correctly you added the die("GOOD"); line so that you dont see the form after it is submitted once. You can do something like the below to achieve this:

$uploadCount = 0;
if(!move_uploaded_file($_FILES['file']['tmp_name'][$key],$dir.'/'.$file_name)){
$uploadCount++;
}
die("$uploadCount file(s) uploaded");

Hope this helps

Upvotes: 1

Related Questions