微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 PHP 从外部 url 下载文件

如何解决使用 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 举报,一经查实,本站将立刻删除。