0

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?

Community
  • 1
  • 1
trejder
  • 17,148
  • 27
  • 124
  • 216

1 Answers1

1

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.

Community
  • 1
  • 1
Dubas
  • 2,855
  • 1
  • 25
  • 37
  • Thanks for your suggestion. However, it does not answer my question, as all functions mentioned by you also output file as string. BTW: you should format your answers using Markdown, to make them more readable. First of all, use links. So: write: `[file_get_contents](http://us1.php.net/manual/en/function.file-get-contents.php)`, instead of: `file_get_contents http://us1.php.net/manual/en/function.file-get-contents.php`, because in your form, entire link is shown, what breaks text flow and formatting. Also, link to English, not Spanish version of pages. – trejder Feb 25 '14 at 08:18
  • Thanks for the edit. I take in consideration for future answers. – Dubas Feb 25 '14 at 08:36