Cache Basics Using PHP and Apache

KeyWords: cache, gzip, zip, php, apache, programming, program, basics, howto, code, file, class, speed, efficiency, server, decrease, load, increase

Cache Basics Using PHP and Apache
by FrosT

Introduction
Working on a new project I found a need to use caching. After searching the internet and asking a few questions on different forums I was able to get a handle on how to properly cache a document using PHP and Apache. Not only will I provide you with document information but the code to a Cache class that I created. Onto the explanation!

Why Cache Files with PHP and Apache?
As most people know caching is not always the best option. You have to ask yourself this questions first, "How dynamic is my content?" If your answer is extremely dynamic, chances are Caching is not for you, at least not in its entirety. Certain pages or files you may not want cached at all, that is perfectly fine. Other files it may make perfect sense to cache them. For example if you have a header and a footer inside PHP files and your header and footer files never change, those can easily be cached without caching the main part of the document. What will caching the header and footer do for you? This would mean less load time for the main page for the user. The only content that has to be generated is the main content. As appose to if the header and footer are not cached every time a call is made for that particular page the header and footer is re-created. This will increase the load time and decrease the pull on your server.

Why Not Cache Files using PHP and Apache?
As stated before some people caching is not a viable option. Meaning their content that is generated is small enough that it would not matter. Or the amount of incoming traffic to their website is not enough to make a difference. A lot of times people will say that it would take too much effort to cache their current site without much of a benefit. This may be true and if that is the case I would say caching is not for you. However if you even think that caching files would help, there is no harm is trying.

The Caching Process with PHP and Apache
The caching process using PHP and Apache is extremely easy. For some people there is a lot of confusion, which hopefully will be avoided using the class I provided. PHP uses a few functions include ob_start() which is designed to capture output before it is displayed on the users screen. The ob functions are very handy when attempting to cache file because you can have any page, whether it be your site or off site captured and cached. Basically what happens is you get all the data you need to display the page, than you call the ob_start() function. As this is happening you print out the entire page just like if you were displaying that page. Once that is completed you call the ob_get_contents() and than ob_end_clean() function which will say "Ok do not capture any more data being output." From here you have the entire page in a string from the ob_get_contents(). Now that we have the whole page in a string we can choose to start that in a text file or in a database.

If you prefer to have all your cached files in a text file than you just use the fopen() and fwrite() functions to do so. If you are like
me and hate having to manage text files etc another viable option is to store the cache in a database. I prefer the database as appose to a text file because a database is much easier to manipulate for me. That is just my preference. Once you have that file cached and stored the process is over, unless you want to take this a step further (which I know you do).

Caching with gZip, PHP and Apache
Since we are already caching the page, let's also make it smaller for storage. This is done using a remarkable function called gZip. gZip basically takes a file and reduces the size. For example at a compression level of 3 (1-9 9 being highest compression) a 48KB file is reduced to 18KB. That is a significant amount of spaced saved. I stated the compression of 3 because using that level gives you plenty of compressions without the heavy load to the server. A level 9 compression uses a lot of system resources to complete. For most people's use a level 3 compression will be sufficient. Lucky for you I included in my Cache class the gZip compression. This will automatically compress any page you cache to gZip format. When retrieving the page for displaying purposes, if the user's browser does not support the gZip format it will unzip the content and display it normally, no functionality will be lost.

Why use gZip as a part of Caching?
After a page is cached the time to load that page is significantly reduced. If you take this process a step further and gZip that page before sending it to the browser the time is again significantly reduced to view that file. As long as the user's browser supports the gZip compression there is no reason to be sending them a 100KB file when it can be 25KB. This will reduce the bandwidth that your site is putting out and increase the speed on the end-user's side. gZip is a major plus no matter how you look at it. With the only issue being if the user's browser does not support gZip all you have to do is code for that. As I stated before I have done this for you already. Using the class I created you will not have to worry about that logic and how to get working correctly.

Ending Notes
Caching with PHP and Apache is an excellent idea for almost any web developer. This will provide you with amazing speeds, lower server strain and less bandwidth used. With the use of gZip everything stated before is increased. The gZip functionality is one that is widely available but not used due to lack of information to developers. That is what I hope to change. The advantages of using gZip are clear cut without any disadvantages. I hope this guide helps you.

Resources:
http://www.emocium.com/files/clCache.phps

Posted by frost on Oct 30th, 2006 17:45 - Subscribe Bookmark and Share


Post a comment:


ReCaptcha:

Posting as anonymous Anonymous guest, why not register, or login now.



Posted by anonymous on February 19th, 2007

Yes,this guide was very helpful to me as a Programmer



Posted by anonymous on September 23rd, 2007

Good stuff...

But two things:

1) Doesn't gzipping the file defeat the purpose of minimizing the CPU time used by the script?
2) Using the database to store the cached version also sounds like it would require more CPU, and would put unnecessary pressure on your database software - another purpose of using caching being to minimize this pressure.



Posted by frost on September 24th, 2007

Reply to Sept23rd.

Agreed, when I wrote this I was not well informed about caching and how it all worked. The GZip compression does little to the CPU, especially if you have it on the right compression setting (3 I believe). The database cache is not logical at all and does not work, especially for a dynamic site.

Really what does make an effect on speed over anything presented here is great coding values. I found that using classes the wrong way can kill your code. But a mixture of classes and functions is needed to have it properly done.

Appreciate the comment.



Posted by anonymous on June 06th, 2008

The hard part for me was to find a solution for the name of the cache files...

I am using a home made CMS and everything is served by my CMS. My script has the entry point in a single file index.php wich is used to serve everything I want. So it is verry easy for me to start building a cache system.

For naming the cache files I founded the next solution:
- i compute the md5() sum from a big string containing all the $_GET and $_POST keys and variables (except session id if any).
- i use this md5() sum for the name of the cache file.
- this md5 sum is later use to detect when the user request is the same with another user request I saved a cache file for...
- if for a particulary md5 sum of $_GET and $_POST variables we have a cache file then the page is served from the cache... if not the cache is generated

Here there is the code to generate the page unique key:

$ts = '';
foreach ( $_GET as $tk => $tv )
$ts .= '/'.$tk.'/'.$tv;
foreach ( $_POST as $tk => $tv )
$ts .= '/'.$tk.'/'.$tv;
return md5($ts);

Any other ideea?



Posted by anonymous on July 25th, 2008

What if in fact my pages are extremely dynamic
and I want to eliminate caching completely;
Is this possible, and how can I do it, or bring it to its bare minimum?



Posted by ruffy on July 25th, 2008

Hi FrosT - I have the same question as anonymous above



Posted by anonymous on September 21st, 2008

見てよ。



Posted by anonymous on September 24th, 2008

GOOD!



Posted by anonymous on April 17th, 2009

Link is broken sad.gif



 

Widget

Hypersmash.com

Extras

  • Not Implemented