【问题标题】:Download Remote File with PHP to Server and finally output to browser使用 PHP 下载远程文件到服务器,最后输出到浏览器
【发布时间】:2018-07-18 01:31:31
【问题描述】:

我想用php下载一个远程文件,保存并输出给用户。我想缓冲文件,因为有些用户可以同时下载同一个文件,节省带宽。

我找到了一个直接从远程服务器下载文件的脚本:

set_time_limit(0);

$url = 'http://example.com/example.zip';
$file = basename($url);

$fp = fopen($file, 'w');

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);

$data = curl_exec($ch);

curl_close($ch);
fclose($fp);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;

【问题讨论】:

  • 您必须在本地缓存文件以供多个用户查看文件。
  • @JasonK 是的。但我认为代码不起作用...

标签: php


【解决方案1】:

这里有一点sn-p。

您在本地检查文件是否存在,如果存在:您获取内容并将其发送给客户端。

否则你发出 curl 请求来获取和存储文件内容

set_time_limit(0);

$url = 'http://example.com/example.zip';

$file = basename($url);
if(!file_exists($file)) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    curl_close($ch);
    file_put_contents($file, $data);
}

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;

【讨论】:

  • 更好的版本应该将文件存储在专用的缓存目录中。也许应该有更好的检查以避免文件名冲突。
  • 如何用这段代码实现它:stackoverflow.com/questions/48668720/…
  • 我看到了这个问题,这很简单......您应该指定从代码中收到的错误消息(不仅是错误代码)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
相关资源
最近更新 更多