PHP使用缓存生成静态页面

静态网址与动态网址

①    静态网址

 

http://localhost/test2.html

 

②    动态网址

http://localhost/showNews.php?id=2&title=hello

 

③    伪静态网址

 

传统的做法->动态网址

http://localhost/showNews.php?lang=cn&class=2&id=100  不好(1. seo不好)

减少sql注入攻击风险改成伪静态网址 http://localhost/news-cn-sport-id100.html


页面静态化的分类

 

为什么要静态化

 

1.      访问php的速度比html慢

 

在apache / bin/ab.exe  可以做压力测试,该工具可以模拟多人,并发访问某个页面.

 

基本的用法

 ab.exe –n 10000 –c 10 http://localhost/test.php

-n 表示请求多少次

-c 表示多少人

 

2.      静态化利于seo

3.     防止sql注入


①    真静态

 

 

方法1: 使用php自身的缓存机制

 

如果要测试php自己的缓存机制, 需要做配置.

php.ini 文件

display_errors=On

output_buffering=Off

error_reproting= 设置错误级别

 

看一段代码,使用缓存时,在发送文件头之前可以显示文字.

<?php

              echo“yyy”;

              header(“content-type:text/htm;charset=utf-8”);

              echo“hello”;

?>


PHP缓存控制的几个函数:

//PHP缓存控制的几个函数:
//开启缓存 [通过php.ini,也可以在页面 ob_start()]
ob_start();
echo "yyy";
header("content-type:text/htm;charset=utf-8");
echo "hello";
//ob_clean函数可以清空 outputbuffer的内容.
//ob_clean();
//ob_end_clean是关闭ob缓存,同时清空.
//ob_clean();
//ob_end_flush() 函数是 把ob缓存的内存输出,并关闭ob
//ob_end_flush();
//ob_end_flush() 函数是 把ob缓存的内存输出,
//ob_flush()函数是输出ob内容,并清空,但不关闭.
ob_flush();
		
echo "kkk";//=>ob缓存.

//header("content-type:text/htm;charset=utf-8");

//ob_get_contents() 可以获取output_buffering的内容.
//$contents=ob_get_contents();

//file_put_contents("d:/log.text",$contents);

下面来看一个实例,用缓存技术,"假如保存的缓存文件未超过30秒,则直接取出缓存文件":

<?php
                $id=$_GET['id'];
                $filename="static_id_".$id.".html";
                $status=filemtime($filename)+30>time();//判断文件创建及修改时间距当前时间是否超过30秒
                if(file_exists($filename)&&$status){
                    $str=file_get_contents($filename);
                    echo $str;
                }else{
                    require_once "SqlHelper.class.php";
                    $sqlHelper=new Sqlhelper();
                    $arr=$sqlHelper->execute_dql2("SELECT * FROM news1 WHERE id=$id");
                    if(empty($arr)){
                        echo "数据为空";
                    }else{
                        /***缓存开始***/
                        ob_start();//下面的内容将存到缓存区中,显示的内容都将存到缓存区
                        echo $arr[0]['tile'];
                        echo "<br/>";
                        echo $arr[0]['content'];
                        $content=  ob_get_contents();//从缓存中获取内容
                        ob_end_clean();//关闭缓存并清空
                        /***缓存结束***/
                        file_put_contents($filename, $content);
                        echo $content;
                    }
                }
                
                
            ?>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值