Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php most memory efficient way to return files

Tags:

php

apache

so i have a bunch of files, some can be up to 30-40mb and i want to use php to handle security of the files, so i can control who has access to them

that means i have a script sort of like this rough example

$has_permission = check_database_for_permission($user, filename);

if ($has_permission) {
   header('Content-Type: image/jpeg'); 
   readfile ($filename);    
   exit; 
} else {
  // return 401 error
}

i would hate for every request to load the full file into memory, as it would soon chew up all the memory on my server with a few simultaneous requests

so a couple of questions

  1. is readfile the most memory efficient way of doing this?
  2. is there some better method of achieving the same outcome, that i am overlooking?

server: apache/php5

thanks

like image 995
bumperbox Avatar asked Jul 14 '26 20:07

bumperbox


1 Answers

readfile is the correct way to do this. By all means don't try to read the file yourself and print it to output--that will consume excessive memory. With the readfile function the contents of the file are buffered directly to output, taking up a trivial amount of transitory memory.

like image 100
JSBձոգչ Avatar answered Jul 16 '26 10:07

JSBձոգչ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!