Home > Code Snippets > Reduce Bandwidth usage in PHP

Reduce Bandwidth usage in PHP

September 22nd, 2008 Leave a comment Go to comments

While searching on the net with the title as search terms, I landed on a page by Anthony Williams, which provoked me to probe more into optimizing all our javascripts too. Since our latest and greatest wordpress implementation at keralaonline, was getting 10K hits per day. I thought to try it out.
By combining the ideas of Anthony Williams and jsmin-php, I wrote a piece, and with the help of a RewriteRule, the famous mod_rewrite module of apache, I could optimize my page fetches a lot. It may take quite a few days before I can come out with any sort of bench marks. But still I am sure there is quite a change.

The basic code was to check HTTP_IF_MODIFIED_SINCE, and behave like a static file, send the appropriate headers. Then I would go ahead and use the minify code to strip off the comments and readability formatting using the jsmin project library. Those who need to implement this should get the jsmin library from the project page.
The code which I wrote to extend is as follows

('DEFAULT_CACHEABLE'24 60 60 15); // setting the future expiry for 15 days
function exitIfNotModifiedSince($last_modified)
$if_modified_since >= $last_modified)
header("HTTP/1.0 304 Not Modified");
$file $_SERVER['DOCUMENT_ROOT'] . str_replace('?' $_SERVER['QUERY_STRING'], ''$_SERVER['REQUEST_URI']);
$file or !file_exists($file)){
header("HTTP/1.0 404 Not Found");
/* first lets check the input file and the if-modified-since */
$page_modified filemtime($file);
header('Last-Modified: ' date("r",$last_modified));
header('Expires: ' date('r'time() + DEFAULT_CACHEABLE)); 
header('Content-type: text/javascript');

The mod_rewrite tag for apache is

RewriteRule (.*)\.js /service.php [L]

The file was hosted in the top level folder, since wordpress already adds the RewriteBase /, so the / was needed before the handler file. We could afford to use the default cache time to be 15 days, planning to make this one month later, after seeing that this brings in a remarkable difference.

Phew! a whopping difference of 130MB in the past 8 hours, since this was implemented. Also the hits are more compared to the previous time span.

Categories: Code Snippets Tags:
  1. No comments yet.
  1. No trackbacks yet.

fifty one − = forty six