Kim Jones Kim Jones - 4 months ago 30
PHP Question

In Multiple file Upload upload single file in new folder in PHP

In PHP I am uploading a multiple file. But I want upload each file in different folder.

I Upload 9 file at a time.

So, Current Scenario is:-
Ex:- Main folder -> pdf-files ->all uploaded pdf files

But I want as:-
Main Folder->pdf-files->New Folder->pdf-file-1.
Again,
Main Folder->pdf-files->New Folder->pdf-file-2.
Main Folder->pdf-files->New Folder->pdf-file-3.
.......
So On

Here is my upload.php file:-

$output_dir = "pdf-files/";
if(isset($_FILES["myfile"]))
{
$ret = array();

$error =$_FILES["myfile"]["error"];
{

if(!is_array($_FILES["myfile"]['name'])) //single file
{
$fileName = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
$ret[$fileName]= $output_dir.$fileName;

}
else
{
$fileCount = count($_FILES["myfile"]['name']);
for($i=0; $i < $fileCount; $i++)
{
$fileName = $_FILES["myfile"]["name"][$i];
$ret[$fileName]= $output_dir.$fileName;
$ret[$fileCount] = $fileCount;
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileName );
}

}
}
echo json_encode($ret);

}


Single file upload:-

require_once('string_helper.php');
$path = strtoupper(random_string('alnum', 10));
$path1 = mkdir("pdf-files/".$path."/");
$output_dir = $path1;
if(isset($_FILES["myfile"]))
{
$ret = array();

$error =$_FILES["myfile"]["error"];
{

if(!is_array($_FILES["myfile"]['name'])) //single file
{
$fileName = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$_FILES["myfile"]["name"]);
$ret[$fileName]= $output_dir.$fileName;

}
}
echo json_encode($ret);
}

Answer

In each iteration of your for loop, add the index to the the output_dir as the name of the New Folder.that way you get a new folder for every file.

$output_dir = "pdf-files/";
if(isset($_FILES["myfile"]))
{
 $ret = array();

 $error =$_FILES["myfile"]["error"];
{

    if(!is_array($_FILES["myfile"]['name'])) //single file
    {
        $fileName = $_FILES["myfile"]["name"];
        move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
        $ret[$fileName]= $output_dir.$fileName;

    }
    else
    {
            $fileCount = count($_FILES["myfile"]['name']);
            for($i=0; $i < $fileCount; $i++)
          {
            $fileName = $_FILES["myfile"]["name"][$i];
            $ret[$fileName]= $output_dir.$fileCount."/".$fileName;
          $ret[$fileCount] = $fileCount;
            move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileCount."/".$fileName );
          }

    }
}
echo json_encode($ret);
}
Comments