PHP downloads remote files in batches and zip compresses and downloads them

PHP downloads remote files in batches and zip compresses and packages the download:

<?php
//示例数据
$files = array(
    'http://example.com/file1.jpg',
    'http://example.com/file2.jpg',
    'http://example.com/file3.jpg'
);
//下载压缩包的文件名
$zipFile = 'download.zip';

$zip = new ZipArchive();
if ($zip->open($zipFile, ZipArchive::CREATE) === true) {
    
    
    $multiHandle = curl_multi_init();
    $curlHandles = array();

    foreach ($files as $index => $fileUrl) {
    
    
        $curlHandles[$index] = curl_init($fileUrl);
        curl_setopt($curlHandles[$index], CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curlHandles[$index], CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curlHandles[$index], CURLOPT_CONNECTTIMEOUT, 10);
        curl_multi_add_handle($multiHandle, $curlHandles[$index]);
    }

    $running = null;
    do {
    
    
        curl_multi_exec($multiHandle, $running);
        curl_multi_select($multiHandle);
    } while ($running > 0);

    foreach ($curlHandles as $index => $handle) {
    
    
        $content = curl_multi_getcontent($handle);
        if (!empty($content)) {
    
    
            $zip->addFromString(basename($files[$index]), $content);
        }
        curl_multi_remove_handle($multiHandle, $handle);
    }

    curl_multi_close($multiHandle);

    $zip->close();

    // 提供下载链接给用户
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="' . $zipFile . '"');
    header('Content-Length: ' . filesize($zipFile));
    readfile($zipFile);

    // 删除临时文件
    unlink($zipFile);
} else {
    
    
    echo 'Failed to create zip archive.';
}
?>

Guess you like

Origin blog.csdn.net/jeesr/article/details/131964000