Heim  >  Artikel  >  Backend-Entwicklung  >  实现PHP页面静态化_PHP教程

实现PHP页面静态化_PHP教程

WBOY
WBOYOriginal
2016-07-20 11:17:55796Durchsuche

 php

	
	//首先查看缓存文件
	if(file_exists("static.html")){
		//缓存时间为3分钟
		if(time()-filemtime("static.html")<60*3){
			//将静态文件内容返回给客户端
			$start_time = microtime();
			echo "我是从静态文件中读取的数据:"."<br/>";
			echo file_get_contents("static.html");
			$end_time   = microtime();
			echo "静态文件使用时间:".($end_time-$start_time);
			exit;
		}
	}
	//如果是首次访问,或者是上次缓存的时间超过3分钟,则从数据库中读取数据
	$host     = "127.0.0.1";
	$user     = "root";
	$password = "123456";
	//记录开始时间
	$start_time = microtime();
	mysql_connect($host,$user,$password);
	mysql_select_db("mydb");
	mysql_query("set names utf8");
	
	$sql 		= "SELECT name,address,email FROM users";
	$resource 	= mysql_query($sql);
	echo "我是从数据库中读取的数据:<br/>";
	ob_start();//打开输出缓冲
	echo "<table border='1'><tr><th>姓名</th><th>地址</th><th>Email</th></tr>";
	//输出取得的信息
	while($userInfo = mysql_fetch_assoc($resource)){
		echo "<tr>";
		echo "<td>".$userInfo['name']."</td>";
		echo "<td>".$userInfo['address']."</td>";
		echo "<td>".$userInfo['email']."</td>";
		echo "</tr>";
	}
	$end_time=microtime();
	$str=ob_get_contents();//获取缓冲区的内容
	ob_end_flush();
	echo "从数据库读数据的时间:".($end_time-$start_time);
	file_put_contents("static.html",$str);
?>

users表中有三条记录,使用的是apache服务。测试结果如下:
从数据库中读数据其平均执行时间为:0.0008041s左右

直接读缓存文件期平均执行时间为:0.0000475

数据库中的记录只有三条,SQL也是简单的单表查询,当表的中记录很多时,或者是多表查询其执行的时间将会更长。缓存虽然能够减少访问数据库的次数,加速响应时间,但缓存并不适合所有的页面。有些页面可能每次访问时其页面的显示的内容就会发生变化,这样的页面显然不能使用缓存。对于那些变化很少的页面才比较适合使用缓存。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/371932.htmlTechArticle? php //首先查看缓存文件if(file_exists(static.html)){//缓存时间为3分钟if(time()-filemtime(static.html)60*3){//将静态文件内容返回给客户端$start_time = mi...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn