PHP file upload questions

I am currently having problems with a user uploading a file stored on my server. I have a code to automatically download a file as soon as the user clicks the download button. It works for all files, but when the size gets over 30MB, it has problems. Is there a user upload limit? Also, I have provided my example code and I am wondering if there is a better practice than using the PHP function "file_get_contents".

Thanks everyone 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);

      

+2


source to share


2 answers


file_get_contents()

will load the entire file into memory - using its log.

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


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

It means:



  • Don't load the whole file into memory
  • No need to echo the content into 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);

      


(By the way: do you really want to turn off errors in this way, using an operator @

? Another solution might be to not display them, but write them to a file - see display_errors

, log_errors

and ) error_log

+6


source


file_get_contents()

extracts the contents of a file to a PHP virtual machine. Use readfile()

to stream a file without reading it.



+1


source







All Articles