Apache 2.4 – Php as file handler and X_Sendfile
I had the following problem. I needed to server files through php for a project. A web server is created to do exactly that. Serve files. But i needed to run my php script as a middleman in order to authorize the file access.
This could be easily done if you redirect all file calls using the .htaccess file to a single php endpoint. So far so gut. But then how could i serve the file with php?
Well a simple solution was to read the file from disk and output directly to the browser. A lot of people were using fopen to read the file and fpassthru. The problem in this situation is that you cannot effectively read huge files and serve them. I mean is like stealing the work of the serve with u very cheap trick. Sorry but i didn’t like this solution.
So next one was to use readfile. This was better because it didn’t produce any memory problems and was sending the data directly to the browser. This is was ok but still i could not let the server do it’s job.
So i discovered a simple apache module called x_sendfile. You had to create a simple Response header and let the apache serve the files directly. Wow i thought this is the right solution alas the module was created for apache 2.2 and hadn’t be updated the last 6 years. Was is secure to use it?
I search for problems and securities issues but could find any. So i decide to try it. I installed it and tried to use it. I added the header but i always received 0 bytes back.
Well i though maybe it is not set? So i looked and there was some .htaccess rules to set it.
XSendFile On XSendFilePath /var/www/files
Unfortunately 500 error was what i received. I found out that the XSendFilePath could not be added on .htaccess. It has to be inserted directly on the apache configuration. Well i could do it and i did, but for a lot of people that they cannot access the apache config files directly it is not a usable method. Maybe somebody will create a new module for the apache 2.4 that we can set it directly in .htaccess
So i added the rules under the directory directive and voila! It worked! Now i am serving the files through php but the files are send direclty from apache server! Well done.
Here you can find an excellent article with thema fast serve files through php