NamePros
Welcome, Guest! Ready to make a name for yourself in the domain business? We welcome both the hobbyist and professional domainer to join the discussion as part of the NamePros community.

Click here to create your profile to start earning reputation for posting, and trader ratings for buying & selling in our free e-marketplace. Build your trader rating with each successful sale. Our system has tracked over 100,000 sales and counting!
FAQ & TOS Register Search Today's Posts Mark Forums Read

Go Back   NamePros.com > Website Development Discussion Forums > Programming > CODE
Reload this Page Make browsers cache your static files with PHP

CODE This forum is for posting code snippets and example scripts that aren't quite tutorials, but could be useful for others. You may post code snippets and/or completed scripts that you've written and want to share here.

Advanced Search
6 members in live chat ~  


Reply
 
LinkBack Thread Tools
Old 09-29-2010, 05:09 PM THREAD STARTER               #1 (permalink)
NamePros Member
Join Date: Mar 2006
Location: (US) Missouri
Posts: 70
Hobnob is on a distinguished road
 



Make browsers cache your static files with PHP


Hey, I had an issue where I needed to make browsers cache my static content (images, css, javascript, etc.) to reduce the server load. However due to the incompetent host I was unable to use Apache's EXPIRES_MODULE, so I came up with this solution:
????: NamePros.com http://www.namepros.com/code/679687-make-browsers-cache-your-static-files.html

Step 1: Create the following directory structure: (static/images, static/css, static/javascript) that is publicly accessible; i.e. http://www.example.com/static/images/xample.jpg

Step 2: Add the following to your .htaccess:
Code:
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(images|css|javascript)/(.*)$ static/static.php?requested_file=$1/$2 [L]
Step 3: Create a static.php file in your "static" directory (http://www.example.com/static/static.php) with this code:
PHP Code:
<?php
/*
 * The aim of this file is to handle static files {images, javascript, css,
 * html, etc.} by setting file expiration headers so that the browsers cache the
 * files instead of requesting them again and again on each request.
 * 
 *       **** THIS IS TO BYPASS THE NEED FOR THE APACHE EXPIRES_MODULE ****
 */

$requested_file $_GET["requested_file"];


/*
 * Make sure a filename was passed and that it exists on the server.
 */
isset($requested_file) or die("Invalid file: {$requested_file}");
is_file($requested_file) or die("The file '{$requested_file}' does not exist.");


/*
 * The accepted mime types
 */
$mime_map = array('bm' => 'image/bmp''bmp' => 'image/bmp',
    
'css' => 'text/css''gif' => 'image/gif''jpeg' => 'image/jpeg',
    
'jpg' => 'image/jpeg''mjpg' => 'video/x-motion-jpeg''xml' => 'text/xml',
    
'png' => 'image/png');

????: NamePros.com http://www.namepros.com/showthread.php?t=679687

/*
 *
 */
class File {
    var 
$filepath$mtime;
    var 
$dirname$name$extension;

    function 
__construct($file) {
        
$this->filepath $file;
        
$this->mtime filemtime($this);

        
$path_parts pathinfo($this);
        
$this->dirname   $path_parts['dirname'];
        
$this->name      $path_parts['basename'];
        
$this->extension strtolower($path_parts['extension']);
    }

    function 
get_etag() {
        return 
md5($this->mtime.$this);
    }

    function 
content() {
        
ob_start();
        
readfile($this);
        
$content ob_get_contents();
        
ob_end_clean();
        return 
$content;
    }

    function 
__toString() {
        return (string)
$this->filepath;
    }
}

$file = new File($requested_file);


/*
 * Make sure the file type is supported
 */
array_key_exists($file->extension$mime_map)
        or die(
"Invalid file type: $file->extension");


/*
 * Caching headers
 */
$etag $file->get_etag();
$time gmdate('r'$file->mtime);

$test1 = isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])
    && 
$_SERVER['HTTP_IF_MODIFIED_SINCE'] == $time;

$test2 = isset($_SERVER['HTTP_IF_NONE_MATCH'])
    && 
str_replace('"'''stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])) == $etag;

if(
$test1 || $test2){
    
header('HTTP/1.1 304 Not Modified');
    exit();
}

header("Last-Modified: $time");
header("Cache-Control: must-revalidate");
header("Expires: $time");
header("Etag: $etag");
header("Content-type: ".$mime_map[$file->extension]);

echo 
$file->content();

?>
Step 4: Call your static content like so: http://www.example.com/images/myimage.jpg, http://www.example.com/css/mystylesheet.css, http://www.example.com/javascript/myscript.js, http://www.example.com/images/subdir/myimage2.jpg

* note this was just a quick and dirty script that has not been optimized in any way, it was tested with the latest version of Firefox and IE. If you see any issues let me know
Last edited by Hobnob; 09-29-2010 at 05:11 PM. Reason: lol, forgot step 4
Hobnob is offline   Reply With Quote
Old 11-05-2010, 11:32 AM   #2 (permalink)
If only you knew...
 
maximum's Avatar
Join Date: Oct 2005
Location: Inside your head...
Posts: 990
maximum has a reputation beyond reputemaximum has a reputation beyond reputemaximum has a reputation beyond reputemaximum has a reputation beyond reputemaximum has a reputation beyond reputemaximum has a reputation beyond reputemaximum has a reputation beyond reputemaximum has a reputation beyond reputemaximum has a reputation beyond reputemaximum has a reputation beyond reputemaximum has a reputation beyond repute
 


Child Abuse Special Olympics Save a Life Baby Health Autism

Thanks for sharing Nice code
__________________
--- The greatest truths ever told, and the greatest lies ever told, all consist of exactly the same three words:
"I LOVE YOU"
--- The best say little, only say what is important.....then they shut up and sit down.
maximum is offline   Reply With Quote
Old 11-30-2010, 05:19 PM   #3 (permalink)
New Member
 
building-guy's Avatar
Join Date: Nov 2010
Posts: 5
building-guy is an unknown quantity at this point
 



Some of the best stuff here seems to get the least eyeballs and responses... once again, great tip, and thanks for sharing :-) GoDaddy doesn't smile on mod_rewrite, but it can handle this!
building-guy is offline   Reply With Quote
Old 12-17-2010, 01:28 PM   #4 (permalink)
Account Suspended
Join Date: Dec 2008
Location: Boston, Ma
Posts: 650
CrackFeed.Com is a name known to allCrackFeed.Com is a name known to allCrackFeed.Com is a name known to allCrackFeed.Com is a name known to allCrackFeed.Com is a name known to allCrackFeed.Com is a name known to all
 



Marrow Donor Program Animal Rescue Autism Autism
...or just use:

Code:
<filesMatch "\.(ico|gif|jpg|jpeg|png|flv|avi|mov|mp4|mpeg|mpg|mp3|pdf|doc|css|js|html|bmp|js|css)$">
  Header set Cache-Control "max-age=86400"
</filesMatch>
in your httpd.conf include file or .htaccess. This tells the browser to cache files.

Your code would waste too much loading time. Good thinking, but needs work.
CrackFeed.Com is offline   Reply With Quote
Old 12-20-2010, 12:32 PM THREAD STARTER               #5 (permalink)
NamePros Member
Join Date: Mar 2006
Location: (US) Missouri
Posts: 70
Hobnob is on a distinguished road
 



Some people don't have the ability to use the Header set (like the customer I wrote that for). As far as the loading time, it's nothing significant and it's less of a load than not caching...

But I'm glad you posted that, it's probably easier for most people.
Hobnob is offline   Reply With Quote
Old 12-20-2010, 12:49 PM   #6 (permalink)
Account Suspended
Join Date: Dec 2008
Location: Boston, Ma
Posts: 650
CrackFeed.Com is a name known to allCrackFeed.Com is a name known to allCrackFeed.Com is a name known to allCrackFeed.Com is a name known to allCrackFeed.Com is a name known to allCrackFeed.Com is a name known to all
 



Marrow Donor Program Animal Rescue Autism Autism
Actually, it works perfect with Chrome, IE7, IE8 and FF3 out of the box and this spead up the loading of Glamourislife.com from 3.6 seconds to 0.13 secnds on a 20 Mb/s connection. For sites using worpress or anything else witha ton of included files, this is vital.
????: NamePros.com http://www.namepros.com/showthread.php?t=679687

Code:
<FilesMatch "\.(ico|gif|jpg|jpeg|png|flv|avi|mov|mp4|mpeg|mpg|mp3|pdf|bmp|js|css|flv|swf|doc)$">
Header set Cache-Control "max-age=7200"
</FilesMatch>

<FilesMatch "\.(xml|txt)$">
Header set Cache-Control "max-age=172800, public, must-revalidate"
</FilesMatch>
 
<FilesMatch "\.(html|htm)$">
Header set Cache-Control "max-age=7200, must-revalidate"
</FilesMatch>
CrackFeed.Com is offline   Reply With Quote
Old 12-30-2010, 06:18 AM   #7 (permalink)
NamePros Regular
 
~ The 34 Year Buzz!!'s Avatar
Join Date: Aug 2006
Location: Cyberspace
Posts: 648
~ The 34 Year Buzz!! has much to be proud of~ The 34 Year Buzz!! has much to be proud of~ The 34 Year Buzz!! has much to be proud of~ The 34 Year Buzz!! has much to be proud of~ The 34 Year Buzz!! has much to be proud of~ The 34 Year Buzz!! has much to be proud of~ The 34 Year Buzz!! has much to be proud of~ The 34 Year Buzz!! has much to be proud of
 



What files get cached by major browsers without any coding?
.jpg/.gif/.png = Yes (correct?)
.ico Yes
.js & .css ??
__________________
Are You Happy Today! :o)
~ The 34 Year Buzz!! is offline   Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools


 
All times are GMT -7. The time now is 07:38 PM.

Domain name forum recommended by Domaining.com Powered by: vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.6.0 Ad Management plugin by RedTyger