如何使用php下载rar文件

时间:2012-06-22 05:54:12

标签: php

我编写了下载rar文件的代码,但工作正常但是

      $name = 'file.rar';
      $data = file_get_contents("file.rar");
      $fh = fopen("$name", 'w') or die("can't open file");
      fwrite($fh, $data);
      fclose($fh);

      header("Cache-Control: public");
      header("Content-Description: File Transfer");
      header("Content-Length: ". filesize("$name").";");
      header("Content-Disposition: attachment; filename=$name");
      header("Content-Type: application/octet-stream; "); 
      header("Content-Transfer-Encoding: binary");
      readfile($name);
      exit;

下载后,在打开该文件时显示错误意外的归档结束, 它不会完全提取给我一些建议,提前谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用网络服务器上的以下代码制作ZIP文件

<?php
$za = new ZipArchive();

$za->open('test_with_comment.zip');
print_r($za);
var_dump($za);
$za->addFile('index.txt', 'newname.txt'); // original file , file to be added in zip

echo "numFiles: " . $za->numFiles . "\n";
echo "status: " . $za->status  . "\n";
echo "statusSys: " . $za->statusSys . "\n";
echo "filename: " . $za->filename . "\n";
echo "comment: " . $za->comment . "\n";

for ($i=0; $i<$za->numFiles;$i++) {
    echo "index: $i\n";
    print_r($za->statIndex($i));
}
echo "numFile:" . $za->numFiles . "\n";
?> 

之后,您可以提供下载链接..

答案 1 :(得分:1)

这个file.rar是通过代码生成的吗? 我已经尝试了没有这些代码的代码

      $data = file_get_contents("file.rar");
      $fh = fopen("$name", 'w') or die("can't open file");
      fwrite($fh, $data);
      fclose($fh);

它对我来说很好。