【问题标题】:Download RAR file from a link (server)从链接(服务器)下载 RAR 文件
【发布时间】:2025-11-22 14:45:01
【问题描述】:

我正在尝试从云端下载 .rar 文件(为简单起见,我使用的是我的 google 驱动器存储),文件正在完美下载,但是一旦我想打开 .rar 文件,它会说“存档格式未知或已损坏”,尝试了所有方法甚至 cURL,但它不想工作, 我只是想知道我的代码中缺少什么,谢谢

<?php

$filename = 'stu.rar';

if ( file_put_contents( $filename,file_get_contents("mygoogleDriveLink/search?q=stu.rar"))) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    //header('Content-Length: '.filesize($filename));
  
    readfile($filename);
    //print_r("this is ".$id);
    
    exit();
   
  
}



else{
    echo  "err";
}

【问题讨论】:

  • 您是否检查了错误日志以查看其中是否有任何报告可以说明这一点?由于它是 Google Drive,我希望它是 SSL,因此希望 file_get_contents 可能需要带有适当 ssl 处理选项的 context 参数
  • 我没有日志报告,只是上面提到的错误我认为我应该包含 google drive API,所以我可以访问文件并下载它们,不是吗?

标签: php file rar


【解决方案1】:

您可以先使用 file_put_contents 将文件保存到服务器,然后再将其流式传输到浏览器。

如果您不需要流式传输到用户的网络浏览器,那么您可以删除从开始流式传输到结束流式传输的代码。

请尝试以下方法:

<?php 
  
// Initialize a file URL to the variable 
$url = 'http://www.xxxxxxxxxxx.com/xxxxx.rar'; 
  
// Use basename() function to return the base name of file  
$file_name = basename($url); 
   
// Use file_get_contents() function to get the file 
// from url and use file_put_contents() function to 
// save the file by using base name 
if(file_put_contents( $file_name,file_get_contents($url))) { 

// File successfully saved in the server

// start streaming . The following is to stream and save to browser

$file_name = $file_name;
$file_url = $file_name;
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"".$file_name."\""); 
readfile($file_url);
exit;
    
/// end streaming   
    
    } 
else { 
    echo "File downloading failed."; 
} 
  
?> 

【讨论】:

  • 您的方法似乎和我的一样有效,但我认为我应该使用 google drive api 来访问文件并下载所需的文件,如果我错了,请纠正我,或者如果你有关于访问云中文件的更好方法(在这种情况下是谷歌驱动器),建议谢谢
最近更新 更多