Serving files with access control (Apache/PHP)

When serving files over PHP often people end up using an incorrect implementation which is open to attacks or has really bad performance (especially with big files). Well you shouldn’t reinvent the wheel every time! When you are using Apache in the first place, why do you need to re-implement the feature, that Apache is best at?

To avoid having to deal with complicated RFCs for HTTP Ranges and Caching use the Apache Module called xsendfileSome apt magic and you are up an running:

apt-get install libapache2-mod-xsendfile
service apache2 restart

Then add this to your vhost configuration:

XSendFile on
XSendFilePath /var/atis/Storage

All set! To send a file via. PHP simply do this:

header('X-Sendfile: ' . $file);
header('Content-Type: ' . contentType($file));
header('Content-Disposition: inline;');

(Make sure you have a function to determine the contenttype of your file)

 

 

Published by

KB

I'm a student at TUM in Computer Science & Pizza eating. Passionate for SRE, beautiful Code and Club Mate.