Search code examples
phpdownloadbinaryfileschunking

Binary-safe function for sending chunks of files in PHP


I've crafted my own version of simple solution, for sending large files in PHP. It uses file chunks. This solution is proted from various sources and I copy-pasted following code to implement "chunking":

$handle = fopen($filename, 'rb'); 

while (!feof($handle))
{ 
    print(@fread($handle, $chunksize));

    ob_flush();
    flush();
} 

fclose($handle);

Since it uses print to send each chunk to the browser, it is very sensitive to character encoding, in which PHP script is encoded. For example, I noticed, that when script is saved in ANSI, downloaded files are corrupted. Only, if I save & upload script encoded in utf-8, file are fine.

Is there a better function, than print to do the same (send piece of file to browser), that would be independend of script file encoding -- because, for example, would force binary transfer to browser?


Solution

  • For small files you should use readfile, that makes all for you to send a file to the client. For really big files these function probably don't work due to memory problems.

    Also there is a function file_get_contents to get all file content into a variable if you require to process it before send. Like readfile is recommended only for "small" files. "small" depends on the memory allowed to run a PHP process (memory_limit parameter in php.ini). Usually servers set it from 8M to 128M and by default is 16MB.