wecenter 页面静态化代码

sl514
sl514 这家伙很懒,还没有设置简介

5 人点赞了该文章 · 3154 浏览

function createHtmlFile($FilePath,$Content){    
    // 去掉文件名中的一些非法符号
    $FilePath = preg_replace('/[ <>\'\"\r\n\t\(\)]/', '', $FilePath);  

    // if there is http:// $FilePath will return its bas path
    // 分隔文件路径,比如/home/xxx/xxx/xxx/xxx.html,
    // 如果是类似http://xxx.com/html/y2012/xxx.html,将传入/html/y2012/xxx.html
    // (http://cn2.php.net/manual/zh/function.explode.php)
    $dir_array = explode("/",$FilePath);  

    //split the FilePath
    $max_index = count($dir_array) ;
    $i = 0;
    $path = $_SERVER['DOCUMENT_ROOT']."/";  // 获取网站的根目录,比如/home/username/

    while( $i < $max_index ){
        $path .= "/".$dir_array[$i];    // 把子目录一级一级加到路径上
        $path = str_replace("//","/",$path);  // 如果有//则替换成/

        if( $dir_array[$i] == "" ){  // 如果这目录值为空则跳过去,这个判断放在循环的最前面可能更合适
            $i ++ ;
            continue;
        }
        // 上面的代码似乎可以写得更精练

        if( substr_count($path, '&') ) return true;  // 如果路径中有&符号,这不好处理,不管了
        if( substr_count($path, '?') ) return true;  // 有?也不管了
        if( !substr_count($path, '.htm') ){     // 如果不包含.htm,原来传了个路径进来
            //if is a directory
            // 如果路径不存在,贱之,并赋读写运行权,如果存在,那八成也是这里贱的
            if( !file_exists( $path ) ){        
                @mkdir( $path, 0777);
                @chmod( $path, 0777 );
            }
        }
        $i ++;  // 这个搞完,继续
    }

    if( is_dir( $path ) ){  //  如果上面折腾完后,发现是个目录,那就是说要创建index.html
        $path = $path."/index.html";
    }
	
    // 如果html页面没创建完整,那还是不管算了
    if ( !strstr( strtolower($Content), '</html>' ) ) return;   

    //if sql error ignore...
    $fp = @fopen( $path , "w+" );   // 好了开始写了,文件在就准备覆盖内容,不在就贱之
    if( $fp ){  // 说明有权限写
        @chmod($path, 0666 ) ;  // 给文件先赋个权限
        @flock($fp ,LOCK_EX );  // 锁定
        // write the file。
        fwrite( $fp , $Content );// 写静态文件内容
        @flock($fp, LOCK_UN);   // 解锁
        fclose($fp);            // 完事
     }
}



上面的这段放在 /system/functions.app.php 里   下面是调用的代码
$Content = TPL::output('tpl模板路径',false);
createHtmlFile("静态文件路径",$Content);
访问一次 就会生成了。   这个是有场景适用的。当然你可以选择部分静态化。 我的做法是把要静态化的部分 静态化到模板目录的文件夹里 然后通过加载模板的方式把内容加载到页面里。
$url111 = 'cache/文章ID.tpl.htm';
TPL::output($url111); 

发布于 2015-08-27 12:34

免责声明:

本文由 sl514 原创发布于 WeCenter ,著作权归作者所有。

登录一下,更多精彩内容等你发现,贡献精彩回答,参与评论互动

登录! 还没有账号?去注册

流落在黄昏
2015-09-08 09:49
收藏了 现在还看不懂
sl514
2015-08-27 14:41
这个有点麻烦。你可以加文件修改时间的判断。如果和当前时间相差一定周期后,就把文件删掉重新生成。
sl514
2015-08-27 14:37
这个是有场景适用的。当然你可以选择部分静态化。 我的做法是吧要静态化的部分 静态化到模板目录的文件夹里 然后通过加载模板的方式把内容加载到页面里。
AWSupport
2015-08-27 14:01
不错,很好的思路
seosns
2015-08-27 12:57
如果内容要要更新呢?