How to setup large file downloads with PHP w/o hogging your servers memory

Posted by Darwin Biler on April 9, 2014

Whether you are trying to secure a set of files so that it can be only accessed when a certain condition are met, or it was just a plain "download counter" feature in your site, PHP developers often resorts to this type of code:

Well for basic stuffs like small images, that works.

But let's say you have a download link for a 10 Gigabyte 1080p video file... uhm

Yes, you will certainly hit the maximum PHP limit. Even if you have that large memory in your server, imagine 10 thousand users hitting the download link simultaneously.

More often, confused website owners resorts to Amazon S3 or other pricey CDN for solution to this, but you know what, before you dump lot of money to those solutions, try this one first, which doesn't cost anything except your time.

There must be better ways of processing downloads in PHP than this.
Fortunately, there is, and I will going to tell you how.

The secret ingredient lies in this little gem : mod_xsendfile

This is an Apache module that you need to install in your web server.
( see https://tn123.org/mod_xsendfile/ how to install it )

Once installed, the only thing you will change in your PHP code is just set a special HTTP header
header('X-Sendfile: /path/to/your/file);

The main advantage of this are:

  • Once the X-Sendfile directive is detected, it will discard any output of your PHP file and send the file right away as if the file was directly clicked
  • The file doesn't have to be publicly accessible - means better security and control on who can access the file
  • You don't have to read the entire file into memory, so its basically faster and doesn't eats up memory
  • Minimal code changes in your existing PHP code
  • End-User will not see the folder path where the file is stored physically in the server
  • It is free

Going back to our example, here is the modified code with the mod_xsendfile header enabled

That's it. You now have a secure file download script by just adding a single line of code!


Did you find this useful?

I'm always happy to help! You can show your support and appreciation by Buying me a coffee (I love coffee!).