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

PHP 从自动下载文件的链接下载文件

如何解决PHP 从自动下载文件的链接下载文件

我正在制作一个网站,您可以通过选择要下载的文件,将多个文件作为 zip 文件一次下载。并下载我想使用外部 URL 的文件。如果我使用的 URL 不会在用户访问该页面自动文件下载到用户 PC,那么所有这些都有效,此类 URL 的示例为 https://example.com/picturetodownload/picture.png

但是,如果我想从一个 URL 下载文件,当用户访问该 URL 时,该 URL 会自动下载该文件,例如,我得到的只是一个名为“download_version=364651”的文件。此类 URL 的示例如下:https://example.com/thingtodownload/download?version=364651

这是我当前的代码

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);

        if ($zip->addFromString(basename($file),$fileContent)!==TRUE) {
            echo "DOESN'T WORK";
            die();
        }
        //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 举报,一经查实,本站将立刻删除。