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 /

# 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 rule above will actually call

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'];

    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.

No comments: