Using the OB cache mechanism of PHP to realize the static of the page
First, let's introduce some common functions commonly used in the OB cache in PHP.
Ob_start (): Turn on caching mechanism
Ob_get_contents (): Gets the contents of the OB cache
Ob_clean () Clears the contents of the OB cache, but does not close the cache
Ob_end_clean () Clears the contents of the OB cache and closes the cache
Ob_flush empty cache, output content, but do not close cache
Ob_end_flush empty cache, output content, and close cache
Flush forces the content in the output cache to flush
According to the HTTP protocol, the response content cannot be output before the response header, so if there is a content output in front of the header () function, there will be an error, but with Ob_start () the response will be placed first in the OB cache, no more messages sent before the hair is sent, Solved the header () error problem!
The following is a method of implementing a page static using the OB cache mechanism that comes with PHP, the sample code is as follows
<?php
$id =$_request[' id '];
Determine if the cache file exists, if present, direct output
if (file_exists (' content '. $id. HTML ')) {
echo file_get_contents (' content '. $id. HTML ');
Return
}
Turn on caching mechanism
Ob_start ();
What you need to query the database
$conn =mysql_connect ("localhost", "root", "root");
Mysql_select (' db ');
mysql_query (' Set names UTF8 ');
$sql = "Select content from table_name where id= $id";
$res =mysql_query ($sql);
$row =mysql_fetch_assoc ($res);
$content = $row [0];
Mysql_free_result ($res);
Mysql_close ($conn);
Echo $content;
Save the output to a file, form a static page, and read the output directly at the next visit
File_put_contents (' content '. $id. HTML ', ob_get_contents ());
?>
As shown in the preceding code:
Save the contents of our query directly to the HTML file, if the file exists, output between, if not, then access the database, execute the corresponding query process
If you want to set the file expiration time, you can add a condition in the IF statement to determine if the cache file expires, time ()-Set expiration
----reproduced from other people's Weibo
Using the OB cache mechanism of PHP to realize the static of the page