詳細検索

How to have multiple file archives downloaded

Avatar
by すがピー
2 min read
Tags php

How to have multiple file archives downloaded
Translated from 日本語 • View original

For example, if you want to download multiple image files at once, you can copy the image files to a temporary directory on the server and archive them for download. However, this will copy the image files one by one, which can strain your storage, and if you have a large number of files, it will take a long time to copy.

So, we will create a symlink and archive it for each directory.

First, create a temporary directory.

$tmp_path = "/tmp/" . uniqid(rand());
$archive_dir = "(directory name you want to specify)";
$tmp_dir = $tmp_path . "/" . $archive_dir;

The reason for separating the path to the temporary directory and the temporary directory name will be explained later.

Next, create a symlink for the image file in the temporary directory you created.

$filelists: List of image file names
$$image_dir: The storage directory of the image file
foreach( $filelists as $image_name ) :
    $target = $image_dir . "/" . $img_name;
    $link   = $tmp_dir . "/" . $img_name;
    symlink($target, $link);
}

Now I will archive this temporary directory as well. Especially in the case of image files, the size does not change much even if compressed, so if you archive them with tar, the processing is faster because there is no compression process. You can archive symbolic links as entities by adding "h" in the tar command options. This is the disgusting thing.

Set the archive file path
$tar_file = tempnam("/tmp", "DOWNLOAD");

Archive with tar command
$command  = "tar chf $tar_file -C $tmp_path $archive_dir"; 
system( $command );

At this time, add "-C" as an option in the tar command. Now go to the specified directory and then process it. This way, you don't have to archive it in the full path of the temporary directory.

After that, just download this file.

Related Articles