PHP实现页面静态化的超简单方法

2019-05-03 02:33:56王旭

纯静态实现,代码和实现逻辑参考:

<?php
/**
 * 触发系统生成纯静态化页面业务逻辑
 * 有3种方案: 
 * 第一:定时扫描程序(利用crontab来处理) 
 * 第二:手动触发方式,人为触发
 * 第三:页面添加缓存时间,在页面中控制时间来操作
*/
//===========================================
//生成纯静态文件步骤
//1、连接数据库,然后从数据库里面获取数据
//2、把获取到的数据填充到模版文件里面
//3、需要把动态的页面转为静态页面,生成静态化文件
//============================================
//PHP实现页面静态化有以下步骤:
//1:A.php请求数据库数据:通过mysql或者mysqli或者PDO扩展
//2:在A.html中输出A.php请求的数据库数据:一般是将将在数据库中取出的数组形式的数据赋予新的数组,并且输出
//3:在A.php中包含A.html文件:直接通过require_once()函数或者inclde_once()
//4:开启数据缓存ob_start()=>获取获取缓存内容并且将数据生成在静态文件中file_put_contents('index.shtml',ob_get_clean());
//header("content-type:text/htm;charset=utf-8");
if(is_file('./index.html') && (time() - filemtime('./index.html') < 1200))
{
  //缓存未失效则直接加载静态文件
  require_once('./index.html');
}
else 
{
  //缓存失效了则重新生成
  // 引入数据库链接操作
  require_once('./db.php');
  $sql = "select * from news where `category_id` = 1 and `status` = 1 limit 4";
  try
  {
      $db = Db::getInstance()->connect();
      $result = mysql_query($sql, $db);
      $newsList = array();
      while($row = mysql_fetch_assoc($result)) 
      {
          $newsList[] = $row;
      }
  }
  catch(Exception $e)
  {
      // TODO
  }
  ob_start();
  require_once('template/index.php');//引入模版文件
  file_put_contents('./index.html', ob_get_contents());//生成静态文件
  //ob_clean();
}

静态页面中局部动态化实现

利用Jquery中的ajax请求文件,获取到返回的JSON数据,然后应用到模版就可以了

伪静态

Nginx服务器默认不支持PATH INFO模式,需要额外配置

Apache伪静态设置

1、开启apache mod_rewrite.so 配置 在 httpd.conf中。

测试的话可以用phpinfo查看,看是否loaded modules 有这个模块

2、inculde conf/extra/httpd-vhosts.conf virtual hosts支持,虚拟域名配置

3、编辑vartual host 文件

4、本机host文件加入配置的域名(如果需要本机测试针对windows)

5、伪静态配置

- 5.1 rewrite engine on
- 5.2编写规则

^/post/([0-9]*).html$ /post.php?id=$1

放在 virtualhost 段中

post.php 中编写

<?php 
echo 'this is '.$_GET['id'];

然后可以访问a.com/123.html 返回的就是this is 123.

相关文章 大家在看