2022年7月26日星期二

[PHP] stream and download large file to client (with low server ram usage)

 header('Content-Disposition: attachment; filename="4k.jpg"');

//define downloaded file name for client

$handle1 = fopen('https://images.pexels.com/photos/1525041/pexels-photo-1525041.jpeg', 'rb');

while (!feof($handle1)) {
$data = fread($handle1, 1024);
echo $data;
flush(); //output to client browser and clear buffer (free RAM)
ob_flush(); //output to client browser and clear buffer (free RAM)
}


fclose($handle1);

//memory usage ===============================================
function formatBytes($bytes, $precision = 2) {
$units = array("b", "kb", "mb", "gb", "tb");

$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);

$bytes /= (1 << (10 * $pow));

return round($bytes, $precision) . " " . $units[$pow];
}

$consolelog = fopen('php://stdout', 'w');

fwrite($consolelog, formatBytes(memory_get_peak_usage()));
fclose($consolelog);

沒有留言:

發佈留言

[Fixed] some windows chrome, scrolling has glitch position not accurate

   [Fixed] some windows chrome, scrolling has glitch position not accurate Smooth Scrolling Flag 📜 Chrome has an experimental "smooth ...