Thursday, September 2, 2010

How to serve web resources through script?

In our test and development environment we needed the assets (pictures, movies, css ...) in order to test the public media site before production. Since the assets in production take around 300 Gb it was unexceptional that assets are copied to every machine. Since all the assets are in assets/ folder on Apache I did the following.

First thing was to tell Apache that every request that goes to assets/ should call the script. I goggled for a while and found this site, that gave me a hint that I needed.The result was the next .htaccess file:

RewriteEngine On
RewriteBase /

# http://httpd.apache.org/docs/2.2/rewrite/rewrite_flags.html
# L - last if match then stop
# NC - nocase case insensitive
# QSA - rewritten query string contains old query data

#RewriteRule ^(assets/.+)$  /file_requester.php?file=$1 [L,NC,QSA]

This rules simple means that every request that goes to assets/ is redirected to file_requester.php script with file request parameter containing whatever follows assets/. For example if request comes to http://myserver.com/assets/videos/jenny.avi rule above will actually call http://myserver.com/file_requester.php?file=videos/jenny.avi

Now the script was called and now it needed to return assets with correct mime type, because we want picture to be picture,video to be video ... Again I found this site with hint I needed. The result was the following script:

if (!file_exists($_REQUEST[file])) {

    $path_parts = pathinfo($_REQUEST[file]);

    //to support spaces in filename we need to encode basename  
    $remotefile = 'http://production'.$path_parts['dirname']."".rawurlencode($path_parts['basename']);

    //make folder
    mkdir('/server_root/'.$path_parts['dirname'], 0700,true);

    //set local path
    $localfile = $path_parts['dirname']."/".$path_parts['basename'];

    //copy
    if (copy($remotefile, $localfile)) {
        echo "Done";
    } else {
        echo "Error";
    }
}

The script above is quite simple. First it checks for file on local server and if it does not exist downloads it from production.Then it sets the mime type and returns the file.

What's up

I haven't posted anything for some time. That is simply because I changed my employee, platform ... and I simply had no time or material to post. After being on Windows for last 12 years and doing mostly .net for last 6 I accepted the opportunity to continue on Linux without focus on single technology, but simply to use the best thing for specific problem. And luckily there are plenty to solve. If diversity and lack of GUI scared me at first I must admit that now after a month at new job, I simply enjoy it. It has proven once again that understanding of standards, principles, algorithms ... is what will give you what you need. Learning the libraries takes time, but my team-mates help me with that.