繁体   English   中英

在 php 中下载 Zip 文件

[英]Download Zip file in php

我想通过我想分配给它的变量 ($direccion) 下载我的 zip 文件,当我尝试这样做时,结果发现该文件已损坏。

$file_name = basename('C:/xampp/htdocs/issv/upload/26908557.zip');
 
   header("Content-Type: application/Zip");
   header("Content-Disposition: attachment; filename=26908557.zip");
   header("Content-Length: " . filesize('C:/xampp/htdocs/issv/upload/26908557.zip'));

  readfile('C:/xampp/htdocs/issv/upload/26908557.zip');
   exit;

那是我的代码,它只能这样工作,但我想把 $direccion 路径放到它上面

$direccion='c:/xampp/htdocs/issv/upload/'.trim($cedula);

这就是我的变量 $cédula 的意思$cedula=$_POST['cedula'];

有许多创建 zip 文件的方法;

$zip_file = '(path)/filename.zip';$dir = plugin_dir_path( __FILE__ );
$zip_file = $dir . '/filename.zip';$zip = new ZipArchive();
if ( $zip->open($zip_file, ZipArchive::CREATE) !== TRUE) {
exit("message");
} $zip->addFile('full_path_of_the_file', 'custom_file_name); $download_file = file_get_contents( $file_url );
$zip->addFromString(basename($file_url),$download_file); $zip->close();

或者干脆这样做:

$url = "http://anysite.com/file.zip";$zip_file = "folder/downloadfile.zip";$zip_resource = fopen($zipFile, "w");$ch_start = curl_init();curl_setopt($ch_start, CURLOPT_URL, $url);curl_setopt($ch_start,CURLOPT_FAILONERROR, true);curl_setopt($ch_start,CURLOPT_HEADER, 0);curl_setopt($ch_start,CURLOPT_FOLLOWLOCATION, true);curl_setopt($ch_start,CURLOPT_AUTOREFERER, true);curl_setopt($ch_start,CURLOPT_BINARYTRANSFER,true);curl_setopt($ch_start,CURLOPT_TIMEOUT, 10);curl_setopt($ch_start,CURLOPT_SSL_VERIFYHOST, 0);curl_setopt($ch_start,CURLOPT_SSL_VERIFYPEER, 0);curl_setopt($ch_start,CURLOPT_FILE,$zip_resource);$page =curl_exec($ch_start);if(!$page){echo "Error :- ".curl_error($ch_start);}curl_close($ch_start);$zip = new ZipArchive;$extractPath = "Download File Path";if($zip->open($zipFile) != "true"){echo "Error :- Unable to open the Zip File";}$zip->extractTo($extractPath);$zip->close();
class FileNotFound extends RuntimeException {}

$downloadUploadedZip = function(string $filename): void {
    $directory = 'C:/xampp/htdocs/issv/upload';

    if (dirname($filename) !== '.') {
        $directory = dirname($filename);
    }

    $filename = basename($filename);
    $filepath = sprintf('%s/%s', $directory, $filename);

    if (file_exists($filepath)) {
        header("Content-Type: application/zip");
        header(sprintf("Content-Disposition: attachment; filename=%s", $filename));
        header(sprintf("Content-Length: %d", filesize($filepath)));

        readfile($filepath);

        exit;
    }

    throw new FileNotFound(sprintf('File %s not found.', $filepath));
};

$downloadUploadedZip('26908557.zip');
$downloadUploadedZip('C:/xampp/htdocs/issv/upload/26908557.zip');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM