This article mainly introduces the method of implementing the page static by the OB cache mechanism of PHP, and the interested friend's reference, I hope to help you.
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 (); The content required 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 at the next visit, read the output file_put_contents directly (' 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
The above this article uses the PHP's OB cache mechanism to implement the page static method is the small part to share to everybody's entire content, hoped can give everybody a reference.
Related recommendations:
Analysis of how PHP uses OB caching mechanism to implement page static solution
Introduction to the PHP OB cache and an explanation of OB functions
The ob cache for PHP