zoukankan      html  css  js  c++  java
  • 利用php的ob缓存机制实现页面静态化

    利用php的ob缓存机制实现页面静态化

    首先介绍一下php中ob缓存常用到的几个常用函数
    ob_start():开启缓存机制
    ob_get_contents():获取ob缓存中的内容
    ob_clean()清除ob缓存中的内容,但不关闭缓存
    ob_end_clean() 清除ob缓存中的内容,并关闭缓存
    ob_flush 清空缓存,输出内容,但不关闭缓存
    ob_end_flush 清空缓存,输出内容,并关闭缓存
    flush强制刷新输出缓存中的内容
    按照http协议的规定,回应内容不能在回应头之前输出,所以,如果在header()函数前面有内容输出,就会出现错误,但使用了ob_start()后就会将回应内容先放在ob缓存    中,不会再消息头发送之前被发送,就解决了header()报错的问题!

    下面说一下用php自带的ob缓存机制实现页面静态化的方法,示例代码如下
    <?php
        
            $id=$_REQUEST['id'];
            
            //判断缓存文件是否存在,如果存在,直接输出
            if(file_exists('content'.$id.'.html')){
                echo file_get_contents('content'.$id.'.html');
                return;
            }
            
            //开启缓存机制
            ob_start();
            
            //到数据库中查询所需要的内容
            $conn=mysql_connect("localhost","root","root");
            mysql_select('db');
            mysql_query('set names utf8');
            
            $sql="select content from table_name where id=$id";
            $res=mysql_query($sql);
            $row=mysql_fetch_assoc($res);
            $content=$row[0];
            
            mysql_free_result($res);
            mysql_close($conn);
            echo $content;
            //将输出的内容保存到文件中,形成静态页面,在下次访问的时候,直接读取输出
            file_put_contents('content'.$id.'.html',ob_get_contents());


    ?>
           
    如上述代码所示:
    将我们查询到的内容直接保存到html文件中,如果文件存在,之间输出,如果不存在,则访问数据库,执行对应的查询过程
    如果要设置文件的过期时间,可以在if语句里面加一个判断条件,用于判断缓存文件是否过期,time()-设置的过期时间


     ----转载自别人的微博

  • 相关阅读:
    CS229 6.4 Neurons Networks Autoencoders and Sparsity
    CS229 6.3 Neurons Networks Gradient Checking
    【Leetcode】【Easy】Min Stack
    【Leetcode】【Easy】Merge Sorted Array
    【Leetcode】【Easy】ZigZag Conversion
    【Leetcode】【Easy】Valid Palindrome
    【Leetcode】【Easy】Reverse Integer
    【Leetcode】【Easy】Palindrome Number
    【Leetcode】【Easy】Length of Last Word
    【Leetcode】【Easy】Remove Nth Node From End of List
  • 原文地址:https://www.cnblogs.com/ds-3579/p/5648801.html
Copyright © 2011-2022 走看看