Useful function for file download (i.e. MP3)

From: Date: Tue, 21 Nov 2006 14:33:41 +0000
Subject: Useful function for file download (i.e. MP3)
Groups: php.general 
Request: Send a blank email to php-general+get-244957@lists.php.net to get a copy of this message
Hey guys, Someone had asked about how to "output an mp3 file"... > readfile(), depending on your PHP version, is going to suck in the whole MP3 before it starts spewing out bytes. I have had this function in my library for quite some time now, can't remember where I got it but it's proven very useful if you want to have a user download a large file without giving a direct link to the file. This function will only use up 1K of memory no matter how big the file is. Enjoy! function readfile_chunked($filename,$retbytes=true) { $chunksize = 1*(1024*1024); // how many bytes per chunk $buffer = ''; $cnt =0; $handle = fopen($filename, 'rb'); if ($handle === false) { return false; } while (!feof($handle)) { $buffer = fread($handle, $chunksize); echo $buffer; ob_flush(); flush(); if ($retbytes) { $cnt += strlen($buffer); } } $status = fclose($handle); if ($retbytes && $status) { return $cnt; // return num. bytes delivered like readfile() does. } return $status; } -B

« previous php.general (#244957) next »