分享常见的几种页面静态化的方法

什么是PHP静态化

PHP静态化的简单理解就是使网站生成页面以静态HTML的形式展现在访客面前,PHP静态化分纯静态化和伪静态化,两者的区别在于PHP生成静态页面的处理机制不同。

为什么要让网页静态化

一、加快页面打开浏览速度,静态页面无需连接数据库打开速度较动态页面有明显提高;
二、有利于搜索引擎优化SEO,Baidu、Google都会优先收录静态页面,不仅被收录的快还收录的全;
三、减轻服务器负担,浏览网页无需调用系统数据库;
四、网站更安全,HTML页面不会受php相关漏洞的影响; 观看一下大一点的网站基本全是静态页面,而且可以减少攻击,防sql注入。

数据库出错时,不影响网站正常访问。
生成html文章虽操作上麻烦些,程序上繁杂些,但为了更利于搜索,为了速度更快些,更安全,这些牺牲还是值得的。

PHP生成静态HTML页面的方法

利用PHP模板生成静态页面

PHP模板实现静态化非常方便,比如安装和使用PHP Smarty实现网站静态化,也可以自己写一套模板解析规则,常见的可以模仿各类cms的模板规则。

1.使用PHP文件读写功能与ob缓存机制生成静态页面
比如某个商品的动态详情页地址是: http://xxx.com?goods.php?gid=112
那么这里我们根据这个地址读取一次这个详情页的内容,然后保存为静态页,下次有人访问这个商品详情页动态地址时,我们可以
直接把已生成好的对应静态内容文件输出出来。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!--?php
$gid = $_GET [ 'gid' ]+0; //商品id
$goods_statis_file = "goods_file_" . $gid . ".html" ; //对应静态页文件
$expr = 3600*24*10; //静态文件有效期,十天
if ( file_exists ( $goods_statis_file )){
   $file_ctime = filectime ( $goods_statis_file ); //文件创建时间
      if ( $file_ctime + $expr -->time()){ //如果没过期
       echo file_get_contents ( $goods_statis_file ); //输出静态文件内容
          exit ;
      } else { //如果已过期
          unlink( $goods_statis_file ); //删除过期的静态页文件
          ob_start();
  
             //从数据库读取数据,并赋值给相关变量
  
             //include ("xxx.html");//加载对应的商品详情页模板
  
             $content = ob_get_contents(); //把详情页内容赋值给$content变量
             file_put_contents ( $goods_statis_file , $content ); //写入内容到对应静态文件中
             ob_end_flush(); //输出商品详情页信息
      }
} else {
  ob_start();
  
  //从数据库读取数据,并赋值给相关变量
  
  //include ("xxx.html");//加载对应的商品详情页模板
  
  $content = ob_get_contents(); //把详情页内容赋值给$content变量
  file_put_contents ( $goods_statis_file , $content ); //写入内容到对应静态文件中
  ob_end_flush(); //输出商品详情页信息
  
}
  
?>

2.使用nosql从内存中读取内容(其实这个已经不算静态化了而是缓存);

以memcache为例:


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!--?php
$gid = $_GET [ 'gid' ]+0; //商品id
$goods_statis_content = "goods_content_" . $gid ; //对应键
$expr = 3600*24*10; //有效期,十天
  
$mem = new Memcache;
$mem --->connect( 'memcache_host' , 11211);
  
$mem_goods_content = $mem ->get( $goods_statis_content );
  
  
  
if ( $mem_goods_content ){
   echo $mem_goods_content ;
} else {
  ob_start();
  
  //从数据库读取数据,并赋值给相关变量
  
  //include ("xxx.html");//加载对应的商品详情页模板
  
  $content = ob_get_contents(); //把详情页内容赋值给$content变量
  $mem ->add( $goods_statis_content , $content , false, $expr );
  ob_end_flush(); //输出商品详情页信息
  
}
  
?>
memcached是键值一一对应,key默认最大不能超过128个字节,value默认大小是1M,因此1M大小满足大多数网页大小的存储。

封装ob缓存成缓存类::
<?php
class Cache {
  /**
  * $dir : 缓存文件存放目录
  * $lifetime : 缓存文件有效期,单位为秒
  * $cacheid : 缓存文件路径,包含文件名
  * $ext : 缓存文件扩展名(可以不用),这里使用是为了查看文件方便
  */
  private $dir;
  private $lifetime;
  private $cacheid;
  private $ext;
  /**
  * 析构函数,检查缓存目录是否有效,默认赋值
  */
  function __construct($dir='',$lifetime=1800) {
    if ($this->dir_isvalid($dir)) {
      $this->dir = $dir;
      $this->lifetime = $lifetime;
      $this->ext = '.Php';
      $this->cacheid = $this->getcacheid();
    }
  }
  /**
  * 检查缓存是否有效
  */
private function isvalid() {
  if (!file_exists($this->cacheid)) return false;
  if (!(@$mtime = filemtime($this->cacheid))) return false;
  if (mktime() - $mtime > $this->lifetime) return false;
  return true;
}
/**
* 写入缓存
* $mode == 0 , 以浏览器缓存的方式取得页面内容
* $mode == 1 , 以直接赋值(通过$content参数接收)的方式取得页面内容
* $mode == 2 , 以本地读取(fopen ile_get_contents)的方式取得页面内容(似乎这种方式没什么必要)
*/
public function write($mode=0,$content='') {
  switch ($mode) {
    case 0:
      $content = ob_get_contents();
      break;
    default:
      break;
  }
 ob_end_flush();
  try {
    file_put_contents($this->cacheid,$content);
  }
  catch (Exception $e) {
    $this->error('写入缓存失败!请检查目录权限!');
  }
}
/**
* 加载缓存
* exit() 载入缓存后终止原页面程序的执行,缓存无效则运行原页面程序生成缓存
* ob_start() 开启浏览器缓存用于在页面结尾处取得页面内容
*/
public function load() {
  if ($this->isvalid()) {
    echo "<span style='display:none;'>This is Cache.</span> ";
    //以下两种方式,哪种方式好?????
    require_once($this->cacheid);
    //echo file_get_contents($this->cacheid);
    exit();
  }
  else {
    ob_start();
  }
}
/**
* 清除缓存
*/
public function clean() {
  try {
    unlink($this->cacheid);
  }
  catch (Exception $e) {
    $this->error('清除缓存文件失败!请检查目录权限!');
  }
}
/**
* 取得缓存文件路径
*/
private function getcacheid() {
  return $this->dir.md5($this->geturl()).$this->ext;
}
/**
* 检查目录是否存在或是否可创建
*/
private function dir_isvalid($dir) {
  if (is_dir($dir)) return true;
  try {
    mkdir($dir,0777);
  }
  catch (Exception $e) {
     $this->error('所设定缓存目录不存在并且创建失败!请检查目录权限!');
     return false;      
  }
  return true;
}
/**
* 取得当前页面完整url
*/
 private function geturl() {
    $url = '';
    if (isset($_SERVER['REQUEST_URI'])) {
      $url = $_SERVER['REQUEST_URI'];
    }
    else {
      $url = $_SERVER['Php_SELF'];
      $url .= empty($_SERVER['QUERY_STRING'])?'':'?'.$_SERVER['QUERY_STRING'];
    }
    return $url;
  }
  /**
  * 输出错误信息
  */
  private function error($str) {
    echo '<div style="color:red;">'.$str.'</div>';
  }
}
使用案例:
//Demo3:
  require_once('cache.inc.php');
  define('CACHEENABLE',true);
  if (CACHEENABLE) {
    $cachedir = './Cache/'; //设定缓存目录
    $cache = new Cache($cachedir,10); //省略参数即采用缺省设置, $cache = new Cache($cachedir);
    if ($_GET['cacheact'] != 'rewrite') //此处为一技巧,通过xx.Php?cacheact=rewrite更新缓存,以此类推,还可以设定一些其它操作
      $cache->load(); //装载缓存,缓存有效则不执行以下页面代码  
  }
  //页面代码开始
  $content = date('H:i:s jS F');//可以使用requesr载入页面代码
  echo $content;
  //页面代码结束
  if (CACHEENABLE)
    $cache->write(1,$content); //首次运行或缓存过期,生成缓存

以上就是页面静态化的相关方法,希望对朋友们有所帮助

猜你喜欢

转载自blog.csdn.net/gaisidewangzhan1/article/details/80295424