Skip to content

Instantly share code, notes, and snippets.

@xcoders-hub
Forked from pigfly88/download_file.php
Created January 4, 2021 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xcoders-hub/4caa507f74b310f3d9dffb8835ce89d2 to your computer and use it in GitHub Desktop.
Save xcoders-hub/4caa507f74b310f3d9dffb8835ce89d2 to your computer and use it in GitHub Desktop.
Download remote file straight to client
function downloadFile($fileUrl)
{
$isRemoteFile = null === parse_url($fileUrl, PHP_URL_HOST) ? false : true;
$fileName = $isRemoteFile ? ltrim(parse_url($fileUrl, PHP_URL_PATH), '/') : pathinfo($fileUrl, PATHINFO_BASENAME);
// 获取文件大小
if ($isRemoteFile) {
$ch = curl_init($fileUrl);
$options = [
CURLOPT_URL => $fileUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
];
curl_setopt_array($ch, $options);
curl_exec($ch);
$fileSize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
} else {
$fileSize = filesize($fileUrl);
}
// 输出响应
ob_start();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Accept-Ranges:bytes");
header('Content-Disposition: attachment; filename="'.$fileName.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . $fileSize);
//readfile($fileUrl);
$file = @fopen($fileUrl,"rb");
while(!feof($file))
{
// 利用输出缓冲增量输出,适合大文件下载
print(@fread($file, 1024*8));
ob_flush();
flush();
}
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment