zoukankan      html  css  js  c++  java
  • PHP缓存

     

    php缓存的方法有很多,最简单的缓存方法就是使用框架。

    先说一下smarty的方法:

    首先设置缓存文件位置:

    1
    $filename = "../cache/huancun.html"; //缓存文件存放的位置

    设置缓存间隔:

    1
    $time = 10; //缓存有效期10秒

    判断缓存文件是否存在,如果缓存文件存在直接调用缓存,如果缓存文件不存在重新缓存:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    if(file_exists($filename) && ((filemtime($filename)+$time)>= time()) )
    {
        //直接调用缓存
        include($filename);
    }
    else
    {
        //重新缓存
        ob_start(); //开启内存缓存
         
        代码部分。。。。。。。<br>     <br><br>     $smarty->display("huancun.html"); 

                  $str = ob_get_contents(); //获取内存中的缓存内容
                  file_put_contents($filename,$str);

    1
    2
    3
        ob_flush(); //关闭内存缓存
         
    }

     如果要使用分页缓存的话需要修改为:

    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
    $p = 1;
    if(!empty($_GET["page"]))
    {
        $p = $_GET["page"];
    }
     
    $filename = "../cache/huancun{$p}.html"; //缓存文件存放的位置
     
    $time = 10; //缓存有效期10秒
     
     
     
    //判断缓存文件是否存在,如果缓存文件存在直接调用缓存,如果缓存文件不存在重新缓存
    if(file_exists($filename) && ((filemtime($filename)+$time)>= time()) )
    {
        //直接调用缓存
        include($filename);
    }
    else
    {
        //重新缓存
        ob_start(); //开启内存缓存
         
        分页代码。。。。。。。。。
     
     
        $smarty->display("huancun.html");
         
        $str = ob_get_contents(); //获取内存中的缓存内容
        file_put_contents($filename,$str);
         
        ob_flush(); //关闭内存缓存
         
    }

     同理,如果没有使用smarty模板。只要将ob_start()与ob_flush()之间的代码修改为普通php代码即可。

  • 相关阅读:
    web三大组件的注册
    springboot 支持 jsp
    redis 储存session
    springboot 做切面
    springboot web静态资源访问
    springboot加载外部配置文件
    springboot 两种配置文件,application.properties ,application.yml ,注入值的两种方式,主动@ConfigurationProperties与被动@value,和其他注解Conditional,PropertySource
    今日立春,SpringBoot! 简单springboot项目搭建开始。
    linux防火墙开放端口
    Don’t try to create file system on an “extended” partition
  • 原文地址:https://www.cnblogs.com/xingyue1988/p/6538481.html
Copyright © 2011-2022 走看看