php頁面靜態化

網站一直在加載,很慢,處理方式多種;php

    0.頁面靜態化;
html

    1.優化數據庫;
mysql

    2.負載均衡;
linux

    3.使用緩存技術
ajax


關於頁面靜態化正則表達式

    使用函數如 file_put_contents($filename,$string);
sql

    php的輸出緩衝區  開啓 5.3之後默認開啓 output_bufferingon 
數據庫

    沒開啓的話能夠用 函數在頁面開始  ob_start();
apache

    eg:    json

ob_start();
...//引文所需靜態化的文件
file_put_contents('index.html',ob_get_contents());
ob_clean();


ob_start();
file_put_contents('index.html',ob_get_clean());

//注意ob_start() 不管php.ini 有沒有開啓 output_buffering 設置,
//最還都要開啓,即便已經爲on ,也是開闢新的輸出緩衝區

關於如何觸發系統生成純靜態頁面

    方式有三種:

    0.頁面添加緩存時間

        用戶訪問如index.php 判斷index.html的修改時間 如當前時間差值 若大於設定的數值學訪問index.php不然訪問靜態頁面

 if(is_file('./index.html')&&time()-filemtime('./index.html')<300){
     require './index.html';
 }else{
     ob_start();
     ......
    file_put_contents('./index.html',ob_get_contents());
 }

    1.手動觸發

        同上不須要判斷

    2.定時任務 crontab  

    定時任務前幾天轉載了一篇博客關於linux定時任務的

    http://my.oschina.net/u/2411815/blog/550833



局部靜態化

    

<script>
	$.ajax({
		url:'xxx.php',
		type:'get',
		dataType:'json',
		error:function(){
		},
		success:function(result){
			if(result.code==1){
				html='';
				$.each(result.data,function(key,value){
					html+='<li>'+value.title+'</li>'
				})
				$("#hot_html").html(html);
			}else{
				//todo
			}
		},
	})
</script>

    

    僞靜態

<?php
/**
* 利用PHP正則表達式來處理僞靜態
* 以http://static.com/newsList.php?type=2&category_id=1 =>  http://static.com/newsList.php/2/1.shtml
*/
//echo 12;
var_dump($_SERVER);

if(isset($_SERVER['PATH_INFO'])) {
	// 解析 /2/1.shtml 匹配pathinfo值,若是沒匹配到則數據不合法,若匹配到作相應處理
	if(preg_match("/^\/(\d+)\/(\d+)(\.shtml)$/", $_SERVER['PATH_INFO'], $pathInfo)) {
		//var_dump($pathInfo);
		$type = $pathInfo[1]; // 類型值
		$categoryId = $pathInfo[2]; // 所在欄目值
		// 引入數據庫連接類
		require_once('./db.php'); 
		$sql = "select * from news where `category_id` = ".$categoryId." and `type` = ".$type." order by id desc";
		try{
			$db = Db::getInstance()->connect();
			$result = mysql_query($sql, $db);
			$newsList = array();
			while($row = mysql_fetch_assoc($result)) {
				$newsList[] = $row;
			}
			var_dump($newsList);
			exit;
		}catch(Exception $e) {
			// TODO
		}
	} else {
		// TODO
		die('url error!');
	}
} else {
	// TODO
	// 錯誤提示,而後跳轉到首頁處理
	die('地址有誤');
}

    路由重寫

        apache 開啓重寫模塊

        http.conf 中修改

            LoadModule rewrite_module modules/mod_rewrite.so

            Include conf/extra/httpd-vhosts.conf

        在httpd-vhosts.conf中設置

<VirtualHost 127.0.0.19:80>
    ServerName www.study.com
    DocumentRoot "C:/wamp/www/study"
    <Directory "C:/wamp/www/study">
        Options Indexes
        Order deny,allow
        allow from all
    </Directory>
    #下面是重寫時候若遇到目錄文件下有該文件則顯示文件
    RewriteEngine on
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
    #下面是重寫規則    //nignx重寫相似
    RewriteRule ^/detail/([0-9]*).html$ /detail.php?id=$1
</VirtualHost>
相關文章
相關標籤/搜索