使用 PHP 从外部 url 下载文件

问题描述

我正在制作一个网站,您可以通过选择要下载的文件,将多个文件作为 zip 文件一次下载。并且要下载我想使用外部 URL 的文件,但是当用户将 zip 文件下载到他们的 PC 时,它完全是空的并且无法打开。我试过调试我的代码,但没有出错。

这是我的代码

if(isset($_POST['files'])) {
$error = ""; //error holder
if(isset($_POST['createzip'])) {
    $post = $_POST; 
    $tmpFile = tempnam('/tmp','');
    if(extension_loaded('zip')) { 
    // Checking ZIP extension is available
    if(isset($post['files']) and count($post['files']) > 0) { 
    // Checking files are selected
    $zip = new ZipArchive(); // Load zip library 
    if($zip->open($tmpFile,ZIPARCHIVE::CREATE)!==TRUE) { 
        // opening zip file to load files
        $error .= "* Sorry ZIP creation Failed at this time";
    }
    foreach($post['files'] as $file) { 
        $context = stream_context_create(
            array(
                "http" => array(
                    "header" => "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/50.0.2661.102 Safari/537.36"
                )
            )
        );
        $fileContent = file_get_contents($file,false,$context);

        $zip->addFile(basename($file),$fileContent); // Adding files into zip
        //echo "WORKS"; This part of the code seems to be working.
        //die();
    }
    $zip->close();
    if(file_exists($tmpFile)) {
        // push to download the zip
        header('Content-type: application/zip');
        header('Content-disposition: attachment; filename=file.zip');
        header('Content-Length: ' . filesize($tmpFile));
        readfile($tmpFile);
        // remove zip file is exists in temp path
        unlink($tmpFile);
    } else {
        exit("Error finding file.");
    }
}
else
$error .= "* Please select file to zip ";
}
else
$error .= "* You dont have ZIP extension";
}
}

谢谢, 尼米图。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)