Ever served large files with PHP? I bet you loved that! Do not worry, I have good news for you! There is a solution (or improvement, whatever you want to call it) to the old way of serving files, which used to look sort of like this:
<?php // Old method, which you shouldn't like anymore! header("Content-type: application/octet-stream"); header('Content-Disposition: attachment; filename="myFile"'); readfile(dirname(__FILE__) . '/myFile');
This guy "Nils Maier" created a nice module for Apache called mod_xsendfile. This module allows you to send a specific header to Apache via PHP, and it's really easy to implement:
<?php // 'New' and improved method! header('X-SendFile: ' . dirname(__FILE__) . '/myFile'); header("Content-type: application/octet-stream"); header('Content-Disposition: attachment; filename="myFile"');
Using this module has a couple of advantages when serving files:
- you can control file-transfers with PHP, without actually serving using PHP
- sets correct cache headers such as Etag and If-Modified-Since as if the file was statically served
- processes cache headers such as If-None-Match or If-Modified-Since
- and more..
There is just one downside to this, you need to install the module into Apache and enable it. Good thing installing it is a breeze!
wget https://tn123.org/mod_xsendfile/mod_xsendfile.c -O mod_xsendfile.c apxs -cia mod_xsendfile.c # Depending on your system, restart Apache /etc/init.d/httpd restart
Now enable XSendFile in your .htaccess (or Apache config):
<IfModule mod_xsendfile.c> XSendFile on </IfModule>
Now you are set up and ready to upload the hell out of your server, without leaning on PHP, enjoy!