Home > Backend Development > PHP Tutorial > Implementing static PHP pages_PHP tutorial

Implementing static PHP pages_PHP tutorial

WBOY
Release: 2016-07-20 11:17:55
Original
858 people have browsed it

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);
?>
Copy after login

There are three records in the users table, using the apache service. The test results are as follows:
The average execution time of reading data from the database is: about 0.0008041s

The average execution time of directly reading cached files is: 0.0000475

There are only three records in the database, and SQL is also a simple single-table query. When there are many records in the table, or multi-table queries, the execution time will be longer. Although caching can reduce the number of database accesses and speed up response times, caching is not suitable for all pages. The displayed content of some pages may change each time they are accessed. Such pages obviously cannot use caching. Caching is more suitable for pages that change rarely.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/371932.htmlTechArticle?php //First check the cache file if(file_exists(static.html)){//The cache time is 3 Minutes if(time()-filemtime(static.html)60*3){//Return the static file content to the client $start_time = mi...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template