前言:
对于网站而言,打开首页的速度极大的影响了用户的观感,网站首页打开过慢可能很多用户会选择离开,而将首页静态化(HTML)可以极大的加快网站打开速度。当然如果你首页存在大量动态内容,此时不建议使用,或者根据自己的网站修改下代码适配。
PHP代码如下:
- 无密码生成HTML
<?php
$nowtime=time();
$pastsec = $nowtime - $_GET["t"];
if($pastsec<600)
{
exit; //10分钟更新一次,时间可以自己调整
}
ob_start(); //打开缓冲区
include("index.php");
$content = ob_get_contents(); //得到缓冲区的内容
$content .= "\n<script language=javascript src=\"new_html.php?t=".$nowtime."\"></script>"; //加上调用更新程序的代码
file_put_contents("index.html",$content);
if (!function_exists("file_put_contents"))
{
function file_put_contents($fn,$fs)
{
$fp=fopen($fn,"w+");
fputs($fp,$fs);
fclose($fp);
}
}
?>
- 有密码生成HTML
<?php
ini_set( 'date.timezone', 'PRC' );
/* 缓存过期时间 单位:秒 */
$expire = 86400;
/* 主动刷新密码 格式:http://test.com/new_html.php?password=123456 */
$password = '123456';
$file_time = @filemtime( 'index.html' );
time() - $file_time > $expire && create_index();
isset( $_GET['password'] ) && $_GET['password'] == $password && create_index();
/*
生成 index.html
*/
function create_index()
{
ob_start();
include( 'index.php' );
$content = ob_get_contents();
$content .= "\n<!-- Create time: " . date( 'Y-m-d H:i:s' ) . " -->";
/* 调用更新 */
$content .= "\n<script language=javascript src='new_html.php'></script>";
ob_clean();
$res = file_put_contents( 'index.html', $content );
if ( $res !== false )
{
die( 'Create successful' );
}
else
{
die( 'Create error' );
}
}
- 选择其中一个将其以utf8编码保存命名为:new_html.php(与更新程序保持一致命名、可自行修改)
- 无密码PHP生成HTML的链接:https://网站域名/new_html.php
- 有密码PHP生成HTML的链接:https://网站域名/new_html.php?password=123456(密码建议自行修改)
- 将网站默认首页设置为index.html而非index.php
作者说明
无密码版本来自于Typecho社区的评论。
有密码版本作者:Scott Yu
本文来自投稿,不代表本站立场,如若转载,请注明出处: