Earlier I explained how you can use X-SendFile to serve large static files more efficiently using PHP and Apache. Serving the files with PHP (and Yii) is really easy and I will explain how to do this after the break.
First off, make sure you have installed mod_xsendfile for Apache, or something similar if you have a different HTTP-server.
Yii has implemented a method for serving files via the X-SendFile HTTP-header, which you can access via:
<?php Yii::app()->request->xSendFile($filePath, $options);
The $filePath parameter represents the full path to the file you wish to serve, the $options parameter is an array:
- saveName: the file name shown to the user, if not set real file name will be used
- mimeType: the mime type of the file, if not set it will be guessed automatically based on the file name, if set to null no content-type header will be sent
- xHeader: appropriate x-sendfile header, defaults to "X-Sendfile"
- terminate: whether to terminate the current application after calling this method, defaults to true
- forceDownload: specifies whether the file will be downloaded or shown inline, defaults to true. (Since Yii version 1.1.9.)
- addHeaders: an array of additional http headers in header-value pairs (available since Yii version 1.1.10)
Note: Depending on the HTTP server this will allow you to send files that are not in the website its path, so make sure you only allow a certain set of files to be sent.
Note: Lighttpd 1.4 and Nginx do not support the X-SendFile HTTP header. Lighttpd 1.4 uses X-LIGHTTPD-send-file and Nginx uses X-Accel-Redirect which you can configure with xHeader property of $options.
<?php Yii::app()->request->xSendFile('/var/www/path/to/file.jpg', array( 'saveName' => 'pretty-file-name.jpg', 'mimeType' => 'image/jpeg', ));
Below some more info on using X-SendFile:
Good luck and happy file serving!
UPDATE 20120229 09:42 Added more details about HTTP server specific X-SendFile headers.