Skip to content

Instantly share code, notes, and snippets.

@atsu666
Created November 28, 2022 04:55
Show Gist options
  • Save atsu666/4d686ca0c93858b8eb6d759af8f67a67 to your computer and use it in GitHub Desktop.
Save atsu666/4d686ca0c93858b8eb6d759af8f67a67 to your computer and use it in GitHub Desktop.
php/Services/Common/Helper.php
public function download($path, $fileName, $extension = false, $remove = false)
{
$fileNameEncode = urlencode($fileName);
$size = filesize($path);
if ($extension) {
$inlineExtensions = configArray('media_inline_download_extension');
$mime = false;
$fp = fopen($path,"rb");
foreach ($inlineExtensions as $i => $value) {
if ($extension == $value) {
$mime = config('media_inline_download_mime', false, $i);
}
}
header("Content-Disposition: inline; filename=\"$fileName\"; filename*=UTF-8''$fileNameEncode");
if ($mime) {
header("Content-Type: $mime");
} else {
header('Content-Type: application/octet-stream');
}
if (isset($_SERVER["HTTP_RANGE"]) && $_SERVER["HTTP_RANGE"]) {
// 要求された開始位置と終了位置を取得
list($start, $end) = sscanf($_SERVER["HTTP_RANGE"],"bytes=%d-%d");
// 終了位置が指定されていない場合(適当に1000000bytesづつ出す)
if (empty($end)) $end = $start + 1000000 - 1;
// 終了位置がファイルサイズを超えた場合
if ($end >= ($size-1)) $end = $size - 1;
// 部分コンテンツであることを伝える
header("HTTP/1.1 206 Partial Content");
// コンテンツ範囲を伝える
header("Content-Range: bytes {$start}-{$end}/{$size}");
// 実際に送信するコンテンツ長: 終了位置 - 開始位置 + 1
$size = $end - $start + 1;
// ファイルポインタを開始位置まで移動
fseek($fp, $start);
}
header('Content-Length: ' . $size);
while (ob_get_level() > 0) {
ob_end_clean();
}
if ($size) echo fread($fp, $size);
fclose($fp);
} else {
header("Content-Disposition: attachment; filename=\"$fileName\"; filename*=UTF-8''$fileNameEncode");
if (strpos(UA, 'MSIE')) {
header('Content-Type: text/download');
} else {
header('Content-Type: application/octet-stream');
}
while (ob_get_level() > 0) {
ob_end_clean();
}
readfile($path);
}
if ($remove) {
Storage::remove($path);
}
die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment