General purpose PHP dynamically generates code for static HTML web pages

  • 2020-03-31 20:23:07
  • OfStack

We know that PHP read MYSQL dynamic display, in the case of heavy traffic, there will be a lot of performance problems, if you rent someone else's virtual host, the CPU will be limited because of excessive CPU consumption, resulting in page can not be accessed. I've shown you a way to dynamically generate HTML from PHP, which can dramatically reduce server CPU load.

First, set the. Htaccess file to convert the parameters of the dynamic call to the static HTML URL address, such as the file in the post directory, forward to the root directory of wp-post.php file, add a similar statement:

RewriteRule ^ post/([a - z0-9 \] + \. HTML) $wp - post. PHP? $1, $2

Then modify the wp-post.php file by adding the following PHP code at the beginning of the file:
 
ob_start(); 
$qstring = isset($_SERVER[%26quot;QUERY_STRING%26quot;]) ? $_SERVER[%26quot;QUERY_STRING%26quot;] : %26quot;%26quot;; 
define(%26quot;HTML_FILE%26quot;, $_SERVER['DOCUMENT_ROOT'].%26quot;/post/%26quot;.$qstring); 

if (file_exists(HTML_FILE)) 
{ 
$lcft = filemtime(HTML_FILE); 
if (($lcft + 3600) %26gt; time()) //Determine whether the last generated HTML file was more than 1 hour, if not, then directly output the file content
{ 
echo(file_get_contents(HTML_FILE)); 
exit(0); 
} 
} 

Next is the existing PHP code, and then at the end of the current code add the following PHP code:
 
define(%26quot;HTMLMETA%26quot;,%26quot;%26lt;!-- this is a real static html file created at %26quot;.date(%26quot;Y-m-d H:i:s%26quot;).%26quot; --%26gt;%26quot;); 
$buffer = ob_get_flush(); 
$fp = fopen(HTML_FILE, %26quot;w%26quot;); 
if ($fp) 
{ 
fwrite($fp, $buffer.HTMLMETA); 
fclose($fp); 
} 

Okay, then look at your static HTML page, and if the comment line appears at the end of the page, you've successfully created the static HTML file.

One application of this method is the one I wrote earlier. WordPress blog stats plugin of the year. This statistical plug-in because query database more than 10 times, many people will have a lot of performance problems when accessing, the use of the dynamic generation of HTML technology I introduced, a day to query once, generate a statistical ranking, perfect solution to the query database performance problems.

Related articles: