搜索
首页后端开发php教程压缩多个CSS与JS文件的php代码

  1. header('Content-type: text/css');
  2. ob_start("compress");
  3. function compress($buffer) {
  4. /* remove comments */
  5. $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
  6. /* remove tabs, spaces, newlines, etc. */
  7. $buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
  8. return $buffer;
  9. }
  10. /* your css files */
  11. include('galleria.css');
  12. include('articles.css');
  13. ob_end_flush();
  14. ?>
复制代码

实例化: test.php

  1. test
复制代码

2. 压缩js 利用jsmin类 来源:http://code.google.com/p/minify/ compress.php

  1. header('Content-type: text/javascript');
  2. require 'jsmin.php';
  3. echo JSMin::minify(file_get_contents('common.js') . file_get_contents('common2.js'));
  4. ?>
复制代码

common.js alert('first js');

common.js alert('second js');

jsmin.php

  1. /**
  2. * jsmin.php - extended PHP implementation of Douglas Crockford's JSMin.
  3. *
  4. * <li> * $minifiedJs = JSMin::minify($js); </li> <li> * </li>
  5. *
  6. * This is a direct port of jsmin.c to PHP with a few PHP performance tweaks and
  7. * modifications to preserve some comments (see below). Also, rather than using
  8. * stdin/stdout, JSMin::minify() accepts a string as input and returns another
  9. * string as output.
  10. *
  11. * Comments containing IE conditional compilation are preserved, as are multi-line
  12. * comments that begin with "/*!" (for documentation purposes). In the latter case
  13. * newlines are inserted around the comment to enhance readability.
  14. *
  15. * PHP 5 or higher is required.
  16. *
  17. * Permission is hereby granted to use this version of the library under the
  18. * same terms as jsmin.c, which has the following license:
  19. *
  20. * --
  21. * Copyright (c) 2002 Douglas Crockford (www.crockford.com)
  22. *
  23. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  24. * this software and associated documentation files (the "Software"), to deal in
  25. * the Software without restriction, including without limitation the rights to
  26. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  27. * of the Software, and to permit persons to whom the Software is furnished to do
  28. * so, subject to the following conditions:
  29. *
  30. * The above copyright notice and this permission notice shall be included in all
  31. * copies or substantial portions of the Software.
  32. *
  33. * The Software shall be used for Good, not Evil.
  34. *
  35. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  36. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  38. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  39. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  41. * SOFTWARE.
  42. * --
  43. *
  44. * @package JSMin
  45. * @author Ryan Grove (PHP port)
  46. * @author Steve Clay (modifications + cleanup)
  47. * @author Andrea Giammarchi (spaceBeforeRegExp)
  48. * @copyright 2002 Douglas Crockford (jsmin.c)
  49. * @copyright 2008 Ryan Grove (PHP port)
  50. * @license http://opensource.org/licenses/mit-license.php MIT License
  51. * @link http://code.google.com/p/jsmin-php/
  52. */
  53. class JSMin {
  54. const ORD_LF = 10;
  55. const ORD_SPACE = 32;
  56. const ACTION_KEEP_A = 1;
  57. const ACTION_DELETE_A = 2;
  58. const ACTION_DELETE_A_B = 3;
  59. protected $a = "\n";
  60. protected $b = '';
  61. protected $input = '';
  62. protected $inputIndex = 0;
  63. protected $inputLength = 0;
  64. protected $lookAhead = null;
  65. protected $output = '';
  66. /**
  67. * Minify Javascript
  68. *
  69. * @param string $js Javascript to be minified
  70. * @return string
  71. */
  72. public static function minify($js)
  73. {
  74. // look out for syntax like "++ +" and "- ++"
  75. $p = '\\+';
  76. $m = '\\-';
  77. if (preg_match("/([$p$m])(?:\\1 [$p$m]| (?:$p$p|$m$m))/", $js)) {
  78. // likely pre-minified and would be broken by JSMin
  79. return $js;
  80. }
  81. $jsmin = new JSMin($js);
  82. return $jsmin->min();
  83. }
  84. /*
  85. * Don't create a JSMin instance, instead use the static function minify,
  86. * which checks for mb_string function overloading and avoids errors
  87. * trying to re-minify the output of Closure Compiler
  88. *
  89. * @private
  90. */
  91. public function __construct($input)
  92. {
  93. $this->input = $input;
  94. }
  95. /**
  96. * Perform minification, return result
  97. */
  98. public function min()
  99. {
  100. if ($this->output !== '') { // min already run
  101. return $this->output;
  102. }
  103. $mbIntEnc = null;
  104. if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
  105. $mbIntEnc = mb_internal_encoding();
  106. mb_internal_encoding('8bit');
  107. }
  108. $this->input = str_replace("\r\n", "\n", $this->input);
  109. $this->inputLength = strlen($this->input);
  110. $this->action(self::ACTION_DELETE_A_B);
  111. while ($this->a !== null) {
  112. // determine next command
  113. $command = self::ACTION_KEEP_A; // default
  114. if ($this->a === ' ') {
  115. if (! $this->isAlphaNum($this->b)) {
  116. $command = self::ACTION_DELETE_A;
  117. }
  118. } elseif ($this->a === "\n") {
  119. if ($this->b === ' ') {
  120. $command = self::ACTION_DELETE_A_B;
  121. // in case of mbstring.func_overload & 2, must check for null b,
  122. // otherwise mb_strpos will give WARNING
  123. } elseif ($this->b === null
  124. || (false === strpos('{[(+-', $this->b)
  125. && ! $this->isAlphaNum($this->b))) {
  126. $command = self::ACTION_DELETE_A;
  127. }
  128. } elseif (! $this->isAlphaNum($this->a)) {
  129. if ($this->b === ' '
  130. || ($this->b === "\n"
  131. && (false === strpos('}])+-"\'', $this->a)))) {
  132. $command = self::ACTION_DELETE_A_B;
  133. }
  134. }
  135. $this->action($command);
  136. }
  137. $this->output = trim($this->output);
  138. if ($mbIntEnc !== null) {
  139. mb_internal_encoding($mbIntEnc);
  140. }
  141. return $this->output;
  142. }
  143. /**
  144. * ACTION_KEEP_A = Output A. Copy B to A. Get the next B.
  145. * ACTION_DELETE_A = Copy B to A. Get the next B.
  146. * ACTION_DELETE_A_B = Get the next B.
  147. */
  148. protected function action($command)
  149. {
  150. switch ($command) {
  151. case self::ACTION_KEEP_A:
  152. $this->output .= $this->a;
  153. // fallthrough
  154. case self::ACTION_DELETE_A:
  155. $this->a = $this->b;
  156. if ($this->a === "'" || $this->a === '"') { // string literal
  157. $str = $this->a; // in case needed for exception
  158. while (true) {
  159. $this->output .= $this->a;
  160. $this->a = $this->get();
  161. if ($this->a === $this->b) { // end quote
  162. break;
  163. }
  164. if (ord($this->a) throw new JSMin_UnterminatedStringException(
  165. "JSMin: Unterminated String at byte "
  166. . $this->inputIndex . ": {$str}");
  167. }
  168. $str .= $this->a;
  169. if ($this->a === '\\') {
  170. $this->output .= $this->a;
  171. $this->a = $this->get();
  172. $str .= $this->a;
  173. }
  174. }
  175. }
  176. // fallthrough
  177. case self::ACTION_DELETE_A_B:
  178. $this->b = $this->next();
  179. if ($this->b === '/' && $this->isRegexpLiteral()) { // RegExp literal
  180. $this->output .= $this->a . $this->b;
  181. $pattern = '/'; // in case needed for exception
  182. while (true) {
  183. $this->a = $this->get();
  184. $pattern .= $this->a;
  185. if ($this->a === '/') { // end pattern
  186. break; // while (true)
  187. } elseif ($this->a === '\\') {
  188. $this->output .= $this->a;
  189. $this->a = $this->get();
  190. $pattern .= $this->a;
  191. } elseif (ord($this->a) throw new JSMin_UnterminatedRegExpException(
  192. "JSMin: Unterminated RegExp at byte "
  193. . $this->inputIndex .": {$pattern}");
  194. }
  195. $this->output .= $this->a;
  196. }
  197. $this->b = $this->next();
  198. }
  199. // end case ACTION_DELETE_A_B
  200. }
  201. }
  202. protected function isRegexpLiteral()
  203. {
  204. if (false !== strpos("\n{;(,=:[!&|?", $this->a)) { // we aren't dividing
  205. return true;
  206. }
  207. if (' ' === $this->a) {
  208. $length = strlen($this->output);
  209. if ($length return true;
  210. }
  211. // you can't divide a keyword
  212. if (preg_match('/(?:case|else|in|return|typeof)$/', $this->output, $m)) {
  213. if ($this->output === $m[0]) { // odd but could happen
  214. return true;
  215. }
  216. // make sure it's a keyword, not end of an identifier
  217. $charBeforeKeyword = substr($this->output, $length - strlen($m[0]) - 1, 1);
  218. if (! $this->isAlphaNum($charBeforeKeyword)) {
  219. return true;
  220. }
  221. }
  222. }
  223. return false;
  224. }
  225. /**
  226. * Get next char. Convert ctrl char to space.
  227. */
  228. protected function get()
  229. {
  230. $c = $this->lookAhead;
  231. $this->lookAhead = null;
  232. if ($c === null) {
  233. if ($this->inputIndex inputLength) {
  234. $c = $this->input[$this->inputIndex];
  235. $this->inputIndex += 1;
  236. } else {
  237. return null;
  238. }
  239. }
  240. if ($c === "\r" || $c === "\n") {
  241. return "\n";
  242. }
  243. if (ord($c) return ' ';
  244. }
  245. return $c;
  246. }
  247. /**
  248. * Get next char. If is ctrl character, translate to a space or newline.
  249. */
  250. protected function peek()
  251. {
  252. $this->lookAhead = $this->get();
  253. return $this->lookAhead;
  254. }
  255. /**
  256. * Is $c a letter, digit, underscore, dollar sign, escape, or non-ASCII?
  257. */
  258. protected function isAlphaNum($c)
  259. {
  260. return (preg_match('/^[0-9a-zA-Z_\\$\\\\]$/', $c) || ord($c) > 126);
  261. }
  262. protected function singleLineComment()
  263. {
  264. $comment = '';
  265. while (true) {
  266. $get = $this->get();
  267. $comment .= $get;
  268. if (ord($get) // if IE conditional comment
  269. if (preg_match('/^\\/@(?:cc_on|if|elif|else|end)\\b/', $comment)) {
  270. return "/{$comment}";
  271. }
  272. return $get;
  273. }
  274. }
  275. }
  276. protected function multipleLineComment()
  277. {
  278. $this->get();
  279. $comment = '';
  280. while (true) {
  281. $get = $this->get();
  282. if ($get === '*') {
  283. if ($this->peek() === '/') { // end of comment reached
  284. $this->get();
  285. // if comment preserved by YUI Compressor
  286. if (0 === strpos($comment, '!')) {
  287. return "\n/*" . substr($comment, 1) . "*/\n";
  288. }
  289. // if IE conditional comment
  290. if (preg_match('/^@(?:cc_on|if|elif|else|end)\\b/', $comment)) {
  291. return "/*{$comment}*/";
  292. }
  293. return ' ';
  294. }
  295. } elseif ($get === null) {
  296. throw new JSMin_UnterminatedCommentException(
  297. "JSMin: Unterminated comment at byte "
  298. . $this->inputIndex . ": /*{$comment}");
  299. }
  300. $comment .= $get;
  301. }
  302. }
  303. /**
  304. * Get the next character, skipping over comments.
  305. * Some comments may be preserved.
  306. */
  307. protected function next()
  308. {
  309. $get = $this->get();
  310. if ($get !== '/') {
  311. return $get;
  312. }
  313. switch ($this->peek()) {
  314. case '/': return $this->singleLineComment();
  315. case '*': return $this->multipleLineComment();
  316. default: return $get;
  317. }
  318. }
  319. }
  320. class JSMin_UnterminatedStringException extends Exception {}
  321. class JSMin_UnterminatedCommentException extends Exception {}
  322. class JSMin_UnterminatedRegExpException extends Exception {}
  323. ?>
复制代码

调用示例:

复制代码


声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
使用数据库存储会话的优点是什么?使用数据库存储会话的优点是什么?Apr 24, 2025 am 12:16 AM

使用数据库存储会话的主要优势包括持久性、可扩展性和安全性。1.持久性:即使服务器重启,会话数据也能保持不变。2.可扩展性:适用于分布式系统,确保会话数据在多服务器间同步。3.安全性:数据库提供加密存储,保护敏感信息。

您如何在PHP中实现自定义会话处理?您如何在PHP中实现自定义会话处理?Apr 24, 2025 am 12:16 AM

在PHP中实现自定义会话处理可以通过实现SessionHandlerInterface接口来完成。具体步骤包括:1)创建实现SessionHandlerInterface的类,如CustomSessionHandler;2)重写接口中的方法(如open,close,read,write,destroy,gc)来定义会话数据的生命周期和存储方式;3)在PHP脚本中注册自定义会话处理器并启动会话。这样可以将数据存储在MySQL、Redis等介质中,提升性能、安全性和可扩展性。

什么是会话ID?什么是会话ID?Apr 24, 2025 am 12:13 AM

SessionID是网络应用程序中用来跟踪用户会话状态的机制。1.它是一个随机生成的字符串,用于在用户与服务器之间的多次交互中保持用户的身份信息。2.服务器生成并通过cookie或URL参数发送给客户端,帮助在用户的多次请求中识别和关联这些请求。3.生成通常使用随机算法保证唯一性和不可预测性。4.在实际开发中,可以使用内存数据库如Redis来存储session数据,提升性能和安全性。

您如何在无状态环境(例如API)中处理会议?您如何在无状态环境(例如API)中处理会议?Apr 24, 2025 am 12:12 AM

在无状态环境如API中管理会话可以通过使用JWT或cookies来实现。1.JWT适合无状态和可扩展性,但大数据时体积大。2.Cookies更传统且易实现,但需谨慎配置以确保安全性。

您如何防止与会议有关的跨站点脚本(XSS)攻击?您如何防止与会议有关的跨站点脚本(XSS)攻击?Apr 23, 2025 am 12:16 AM

要保护应用免受与会话相关的XSS攻击,需采取以下措施:1.设置HttpOnly和Secure标志保护会话cookie。2.对所有用户输入进行输出编码。3.实施内容安全策略(CSP)限制脚本来源。通过这些策略,可以有效防护会话相关的XSS攻击,确保用户数据安全。

您如何优化PHP会话性能?您如何优化PHP会话性能?Apr 23, 2025 am 12:13 AM

优化PHP会话性能的方法包括:1.延迟会话启动,2.使用数据库存储会话,3.压缩会话数据,4.管理会话生命周期,5.实现会话共享。这些策略能显着提升应用在高并发环境下的效率。

什么是session.gc_maxlifetime配置设置?什么是session.gc_maxlifetime配置设置?Apr 23, 2025 am 12:10 AM

thesession.gc_maxlifetimesettinginphpdeterminesthelifespanofsessiondata,setInSeconds.1)它'sconfiguredinphp.iniorviaini_set().2)abalanceIsiseededeedeedeedeedeedeedto to to avoidperformance andununununununexpectedLogOgouts.3)

您如何在PHP中配置会话名?您如何在PHP中配置会话名?Apr 23, 2025 am 12:08 AM

在PHP中,可以使用session_name()函数配置会话名称。具体步骤如下:1.使用session_name()函数设置会话名称,例如session_name("my_session")。2.在设置会话名称后,调用session_start()启动会话。配置会话名称可以避免多应用间的会话数据冲突,并增强安全性,但需注意会话名称的唯一性、安全性、长度和设置时机。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)