Aleman
Aleman

Reputation: 101

Merging file chunks PHP

I have implemented a library (Dropzone.js) to upload large files to my server from my application (divided into pieces of 5 Mb) and works perfectly.

If I wanted to download the file from the server. how to join the pieces with PHP?

enter image description here

(Not always the file uploaded is a .rar, it can be any type of file)

I trying something like this.

<?php

$target_path = 'upload/';
$directory = opendir($target_path); //get all files in the path
$files = array() ;
$c =0;
while ($archivo = readdir($directory)) //
{
    if (is_dir($archivo))//check whether or not it is a directory
    {

    }
    else
    {
        $files= $target_path.$archivo;
        $c++;
    }
}

$final_file_path =$target_path;
$catCmd = "cat " . implode(" ", $files) . " > " . $final_file_path;
exec($catCmd);
?>

Upvotes: 2

Views: 765

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

Your main issue is that you need to build an array but you overwrite $files each iteration, so:

$files[] = $target_path.$archivo;

However, you can make it much shorter:

$target_path = 'upload';
$files = array_filter(glob("$target_path/*"), 'is_file');
$catCmd = "cat " . implode(" ", $files) . " > $target_path/NEW";
exec($catCmd);
  • glob for all files in the directory
  • filter on only the entries that is_file
  • implode and execute as you were
  • specify a name for the new file, I used NEW

Upvotes: 4

Related Questions