views:

145

answers:

3

What is the best practice when serving files from the Zend Framework MVC? These files have to be served from the MVC as they are protected.

I know you can read in the file and place it into the Response object but this seems like a bad practice as you would be reading the entire file into memory then serving it. Right now I usually do:

header('Content-type: image/jpeg');
fpassthru(fopen($path, 'rb'));
exit;

But this also doesn't seem right as I'm stopping the execution of the script. Any suggestions?

+1  A: 

You could try using the X-Sendfile header. It is supported by lighttpd and newer versions of apache. Basically the webserver will replace the output of the script with the file you specified. The downside being that it is specific to the configuration of the webserver, so you may be on a host that doesn't support it.

envalid
This would be nice, but we have enough problems with server configurations being out of whack here that I don't want to rely on that.
smack0007
+1  A: 

I would suggest building a super-simple script for retrieving files based on ticket system like in CMS you generate ticket to DB - filename, unique-hash and than redirect to the super-simple file-retieving script (file.php?hash=asd52ad3as1g5). It will get the hash from query and based on it fetch the real filename and push that to output as you have written using fpassthru. The hash need to be unique and hard to guess...

Tomáš Fejfar
but just if you need to finish you script, I think it's nothing wrong with exit() it's used in internal ZF redirects as well ;)
Tomáš Fejfar
+1  A: 

I see nothing wrong with just exit(); What you will need to be careful of is any output buffering layers you may have on (gzip compression, etc). Large files could blow up those buffers pretty quick, so you'll want to close them out and potentially 'chunk' your output with a fopen/fread loop.

Justin