views:

48

answers:

2

Hey All!

I am currently running into some problems with user's downloading a file stored on my server. I have code set up to auto download a file once the user hits the download button. It is working for all files, but when the size get's larger than 30 MB it is having issues. Is there a limit on user download? Also, I have supplied my example code and am wondering if there is a better practice than using the PHP function 'file_get_contents'.

Thank You all for the help!

$path = $_SERVER['DOCUMENT_ROOT'] . '../path/to/file/';
$filename = 'filename.zip';
$filesize = filesize($path . $filename);
@header("Content-type: application/zip");
@header("Content-Disposition: attachment; filename=$filename");
@header("Content-Length: $filesize")
echo file_get_contents($path . $filename);
+1  A: 

file_get_contents() pulls the file contents into the PHP VM. Use readfile() to stream the file without reading it.

Ignacio Vazquez-Abrams
+6  A: 

file_get_contents() will load the whole file into memory -- using a log of it.

And, in PHP, the amount of memory a script can used is limited (see memory_limit) -- which might explain that your download script doesn't work for big files.


Using readfile(), instead, might be a better choice : it will read the file, and directly send its content to the output buffer.

This means :

  • Not loading the whole file into memory
  • Not having to echo the content you've loaded in memory.

Just using something like this should be OK :

$path = $_SERVER['DOCUMENT_ROOT'] . '../path/to/file/';
$filename = 'filename.zip';
$filesize = filesize($path . $filename);
@header("Content-type: application/zip");
@header("Content-Disposition: attachment; filename=$filename");
@header("Content-Length: $filesize")
readfile($path . $filename);


(BTW : do you really want to silence errors this way, with the @ operator ? Another solution could be to not display them, but log them to a file -- see display_errors, log_errors, and error_log)

Pascal MARTIN
Pascal, Thank you for the help and great info. Looks like my script limit is large enough and readfile function is working fine. I removed the @ operator to turn errors back on. Although, I am still having problems with my larger files downloading. Any more thoughts?
nsearle