I want to download a remote file with php, save it and output it to the user. I want to buffer files because some users can download the same file at the same time and save bandwidth.
I found a script to download a file from remote server directly:
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;
答案 0 :(得分:0)
这里有一个小片段。
如果文件存在,则在本地检查,如果存在:您获取内容并将其发送到客户端。
否则,您将获取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;