tags:

views:

43

answers:

2

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

+5  A: 

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.

JSBangs
+1 deleting my answer, it's obvious when you look at it.
Pekka
I was typing this comment to Pekka's answer while it was deleted: "readfile() does this, while coping the file directly from the file into the memory for the webserver. With your loop the data is copied from the file into PHP memory and from PHP memory to the web server.Aditionally with readfile() the system can choose a block size which works best, which might not be 8192"
johannes
Just remember that during the whole time a user is downloading a file one PHP-process will be blocked. So if you have 8 PHP-processes running on your server and 8 users are downloading files, your website will be unable to handle any more requests that involve PHP, which usually means the website will freeze completely.
0scar
+3  A: 

The fastest way is when you can relay this to the webserver. The webserver can use the sendfile() call to ask the operating system kernel to directly copy from a file to the network stream. for instance when using lighttpd there is a way that PHP can signal the server to take over and do the sendfile trick:

http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file

johannes
unfortunately for me i need to the software to run on multiple servers, and i can't guarantee that module will be available on them all. but definitely something i will look at, thanks
bumperbox