Php uses the ob cache mechanism to achieve full page static solution and ob Cache
First, we will introduce several common functions frequently used in ob cache in php.
Ob_start (): Enable the cache mechanism
Ob_get_contents (): Get the content in the ob Cache
Ob_clean () clears the content in the ob cache, but does not disable the cache.
Ob_end_clean () clears the content in the ob cache and closes the cache.
Ob_flush clears the cache and outputs the content, but does not disable the cache.
Ob_end_flush clear cache, output content, and disable Cache
Flush force refresh the content in the output Cache
According to the http protocol, the response content cannot be output before the response header. Therefore, if there is content output before the header () function, an error will occur, but ob_start () is used () then, the response content will be placed in the ob cache first, and will not be sent before the message header is sent. This solves the problem of header () error!
The following describes how to use the ob cache mechanism provided by php to achieve Static Page
Code school php
1 <? Php 2 3 $ id = $ _ REQUEST ['id']; 4 5 // determine whether the cached file exists. If yes, output 6 if(file_exists('content'.$id.'.html ')) {7 echo file_get_contents('content'.$id.'.html '); 8 return; 9} 10 11 // enable cache mechanism 12 ob_start (); 13 14 // query the required content in the database. 15 $ conn = mysql_connect ("localhost", "root", "root"); 16 mysql_select ('db '); 17 mysql_query ('set names utf8'); 18 19 $ SQL = "select content from table_name where id = $ id"; 20 $ res = mysql_query ($ SQL); 21 $ Row = mysql_fetch_assoc ($ res); 22 $ content = $ row [0]; 23 24 mysql_free_result ($ res); 25 mysql_close ($ conn); 26 echo $ content; 27 // Save the output content to the file to form a static page. During the next visit, you can directly read the output 28 file_put_contents('content'.$id.'.html ', ob_get_contents (); 29 30 31?>
As shown in the code above:
Save the queried content directly to the html file. If the file exists, output the content between them. If the file does not exist, access the database and execute the corresponding Query Process.
If you want to set the file expiration time, you can add a judgment condition in the if statement to determine whether the cache file expires, time ()-set expiration time