-
-
Save xcoders-hub/4caa507f74b310f3d9dffb8835ce89d2 to your computer and use it in GitHub Desktop.
Download remote file straight to client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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