As you may know, our friend Jan Kneschke is the creator of lighttpd (called „lighty“), a superb OpenSource webserver (designed for speed and easyness) where we provide exclusively consulting and implementation services for.
Some days ago I stumbled upon an old entry of Jan in lighty’s life, called „X-Sendfile“. There he explains how to speed up the delivery of (large) files with lighttpd instead of PHP (YES, lighttpd is very fast – for one customer we created an ImageServer with pure lighty that replaced a 4-server-cluster with Apache and now has 1 server with lighttpd (which is boring around at low load). The box makes 180 Mio. requests per month).
It makes use of the X-Sendfile: (upon lighttpd V1.5) or X-LIGHTTPD-send-file: (prior to V1.5) header lines. In fact, your PHP script does only the following things – for example in a Media Asset Management System:
- check ACL for the particular user if he has the right to download the file
- search for the original filename in the database it had when the file was uploaded
- set the appropriate headers (the file may have a crypting filename on the disk, i.e. not the original filename as it was uploaded for)
output file via readfile() and the like- set the X-LIGHTTPD-send-file: or X-Sendfile: header
- exit your script – let lighttpd take care about delivering the file to the client and save your PHP FCGI Binary for the next real application request
As you see, lighty will handle the delivery of the file itself. In order to support the hand-over to lighttpd you need to activate support for X-sendfile in the configuration:
fastcgi.server = { ".php" => { "192.168.0.1" => { # .... "allow-x-send-file" => "enable" } } }
Here’s a short example of a PHP script that lets lighttpd deliver the file:
<?php /** * lighttpd's feature of X-Sendfile explained. * * @author Björn Schotte <schotte@mayflower.de> */ // as this is an example, here's the static file. Usually, you may // have something like /download.php?file_id=500 etc. This file here is 126 MB big $file_on_harddisk = "/data/vhosts/bjoern/htdocs/acbd18db4cc2f85cedef654fccc4a4d8download.tar.gz"; $file_to_download = "download.tar.gz"; // try to fake a "ACL authentication". This is rather simple, so // replace it with your own ACL routine if ( !empty($_GET['authenticated']) && $_GET['authenticated'] == 1) { header( "Content-Disposition: attachment; filename=\"" . $file_to_download . '"' ); Header( "X-LIGHTTPD-send-file: " . $file_on_harddisk); } else { print "Sorry, you don't have permissions to download this file!<br />\n"; }
Happy lightning!
Schreibe einen Kommentar