php 页面静态化与伪静态

1、介绍

 说明:页面静态化,就是将PHP查询结果保存到一个静态的html文件中,将来用户访问的时候可以直接访问该静态html文件即可。

 优点:缓存减轻了数据库的压力,但是服务器的压力依然存在。

 适用场景:查询比较频繁,不经常更新的内容,可以使用页面静态化,例如:新闻,文章等,但是数据经常变化的,如股票,天气等,就不适合使用页面静态化

 实现:使用ob缓冲机制结合file_put_contents函数来实现。

ob缓冲:是服务器向客户端响应数据时,存储响应数据的临时空间。

开启ob服务

 

 2、相关函数

ob_start():开辟一个新的缓冲区域,只要ob_start()一次,就会在PHP的缓存中开辟一块缓冲区域而且,服务器输出的内容会先输出到缓冲区域中再组客户端响应。

服务器向客户端响应数据的方式:echo、var_dump、require、include

<?php
header('content-type: text/html;charset=utf8');
ini_set('display_errors', true);
ob_start();
echo 'are you ok???';
ob_clean();
//不会输出are you ok??? 因为输出的内容存到了缓存区域,然后又清除了
?>

ob_get_contents():获取缓冲区域里面的内容

ob_get_length():获取缓冲区域里面内容的长度

<?php
header('content-type: text/html;charset=utf8');
ini_set('display_errors', true);
ob_start();
echo 'are you ok????';
$result = ob_get_contents();
$len = ob_get_length();
ob_clean();
echo $result;
echo $len;
//输出 are you ok????14
?>

注意:如果里面是Php代码将获取不到如<?php echo 'ok' ?>

ob_flush():直接把缓冲区域刷出去

ob_get_flush():功能有些类似ob_get_contents() 是获取缓冲区域里的内容

<?php
header('content-type: text/html;charset=utf8');
ini_set('display_errors', true);
require_once('./vendor/autoload.php');
ob_start();
require('./sendMsg.php');
//ob_flush();             //直接会展示页面
$result = ob_get_flush();
ob_clean();
echo $result;            //输出页面
?>

ob_clean():清空缓冲区域的内容

ob_get_clean():获得清空的缓冲区域的内容

<?php
header('content-type: text/html;charset=utf8');
ini_set('display_errors', true);
require_once('./vendor/autoload.php');
ob_start();
require('./sendMsg.php');
$result = ob_get_clean();
echo $result;            //输出页面
?>

注意ob_clean()只是清除离ob_clean最近的缓冲内容

 3、利用ob_gzhandler对缓冲进行压缩

<?php
header('content-type: text/html;charset=utf8');
ini_set('display_errors', true);
ob_start('ob_gzhandler');
ob_implicit_flush(false);
require('./sendMsg.php');
echo str_repeat(ob_get_contents(), 100);
?>

 4、伪静态

说明:所谓的伪静态是假的静态,伪静态的效果是这个样子:http://localhost/0423/question/add.html访问的时候,会进入question控制器的add方法中,但是给用户的感觉是静态页面,实际上还是会动态解析,所以称之为伪静态index.php?c=question&a=addAction。

优点:1、有利于用记忆;2、有利于seo;

 主要采用的是$_SERVER[PATH_INFO]进行拆分解析。

<?php
header('content-type: text/html;charset=utf8');
ini_set('display_errors', true);
var_dump($_SERVER['PATH_INFO']);
?>

输出  C:wamp64wwwlearncall.php:4:string'/test/a/b/c' (length=11)

原文地址:https://www.cnblogs.com/rickyctbu/p/11515356.html