seajs模块php合并输出

总结下之前做过的seajs项目,在不用构建工具情况下,单纯用了php做合并js模块做输出。类似 http://www.XXX.com/min/f=ui/page/hall/applib/detailInfo.js,直接请求 min目录下的 index.php ,然后php将全部require 的js 一起压缩输出,代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
header('Content-Type:application/x-javascript');
header('Cache-Control:max-age=1800');
date_default_timezone_set('UTC');
$time = date('D, d M Y H:i:s', time() + 1800) . ' GMT';
header("Expires: $time");

define("BD","/data1/XXX/script/");
$file = $_GET['f'];

if(strpos(realpath(BD.$file),realpath(BD)) === false)
{
echo 'you can not read parent directory.';
exit;
}

$buf = '';
$filemap = array();
function fetchfile($path)
{
global $filemap;
if(!file_exists($path))
{
echo 'file'.$path.'is not exist';
return;
}
if(isset($filemap[$path]))
{
return;
}

$filemap[$path] = true;
$matches = array();
$filestr = file_get_contents($path);
global $buf;
if($filestr)
{
$buf .= $filestr;
}
else
{
return;
}

preg_match_all("/require\([^\(\)]*\)/",file_get_contents($path),$matches);
for($i = 0;$i < count($matches[0]);$i++)
{
$p = '';
if(strpos($matches[0][$i],"'") !== false)
{
$p = explode("'",$matches[0][$i]);
$p = BD.$p[1];
}
else if(strpos($matches[0][$i],'"') !== false)
{
$p = explode('"',$matches[0][$i]);
$p = BD.$p[1];
}
if($p !== '')
{
if(strpos($p,'.js') !== false)
{
fetchfile($p);
}
else
{
fetchfile($p.'.js');
}
}

}
}
function ob_gzip($content)
{
if( !headers_sent() && extension_loaded("zlib") && strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip") && $content != '')
{
extension_loaded("zlib");
$content = gzencode($content);
header("Content-Encoding: gzip");
header("Vary: Accept-Encoding");
header("Content-Length: ".strlen($content));
}
return $content;
}
fetchfile(BD.$file);
$buf = ob_gzip($buf);
echo $buf;
?>