php使用gzip压缩传输js和css文件的方法


Posted in PHP onJuly 29, 2015

本文实例讲述了php使用gzip压缩传输js和css文件的方法。分享给大家供大家参考。具体如下:

<?php
  /**
   * 完整调用示例:
   * 1、combine.php?t=j&b=public&fs=jslib.jquery,function
   * 
   * 该例子调用的是网站根目录下的public/jslib/jquery.js和public/function.js
   * 
   * 2、combine.php?t=j&fs=jslib.jquery,function
   * 
   * 该例子调用的是网站根目录下的jslib/jquery.js和function.js
   * 
   * 3、combine.php?t=c&b=public.css&fs=common,index
   * 
   * 该例子调用的是网站根目录下的public/css/common.css和public/css/index.css
   * 
   * 4、combine.php?t=c&fs=css.common
   * 该例子调用的是网站根目录下的css/common.css
   * 
   * 注:多个文件名之间用,分隔;只有一个文件名最后不要有,
   *   用,分隔的多个文件会被压缩进一个文件,一次性传给浏览器
   **/
  $is_bad_request=false;
  $cache = true;
  $doc_root_uri=$_SERVER['DOCUMENT_ROOT'].'/';
  $cachedir = $doc_root_uri . 'public/cache';
  //文件类型,j为js,c为css
  $type=isset($_GET['t'])?($_GET['t']=='j'||$_GET['t']=='c'?$_GET['t']:''):'';
  //存放js和css文件的基目录, 例如:?b=public.js 代表的是/public/js文件夹,出发点是网站根目录
  //基目录参数不是必须的,如果有基目录那么这个基目录就会附加在文件名之前
  $base =isset($_GET['b'])?($doc_root_uri.str_replace('.','/',$_GET['b'])):$doc_root_uri;
  //文件名列表,文件名不带后缀名.比如基目录是
  //文件名的格式是 :基目录(如果有)+文件包名+文件名
  //例如:类型是j,
  //   文件名public.js.jquery
  //   如果有基路径且为public,
  //   那么转换后的文件名就是/public/public/js/jquery.js
  //   如果没有基路径
  //   那么转换后的文件名就是/public/js/jquery.js
  //多个文件名之间用,分隔
  $fs=isset($_GET['fs'])?str_replace('.','/',$_GET['fs']):'';
  $fs=str_replace(',','.'.($type=='j'?'js,':'css,'),$fs);
  $fs=$fs.($type=='j'?'.js':'.css');
  if($type==''||$fs==''){$is_bad_request=true;}
  //die($base);
  if($is_bad_request){header ("HTTP/1.0 503 Not Implemented");}
  $file_type=$type=='j'?'javascript':'css';
  $elements = explode(',',preg_replace('/([^?]*).*/', '\1', $fs));
  // Determine last modification date of the files
  $lastmodified = 0;
  while (list(,$element) = each($elements)) {
    $path =$base . '/' . $element;
    if (($type == 'j' && substr($path, -3) != '.js') || 
      ($type == 'c' && substr($path, -4) != '.css')) {
      header ("HTTP/1.0 403 Forbidden");
      exit;  
    }
    if (substr($path, 0, strlen($base)) != $base || !file_exists($path)) {
      header ("HTTP/1.0 404 Not Found");
      exit;
    }
    $lastmodified = max($lastmodified, filemtime($path));
  }
  // Send Etag hash
  $hash = $lastmodified . '-' . md5($fs);
  header ("Etag: \"" . $hash . "\"");
  if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && 
    stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) == '"' . $hash . '"') 
  {
    // Return visit and no modifications, so do not send anything
    header ("HTTP/1.0 304 Not Modified");
    header ("Content-Type: text/" . $file_type);
    header ('Content-Length: 0');
  } 
  else
  {
    // First time visit or files were modified
    if ($cache) 
    {
      // Determine supported compression method
      $gzip = strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');
      $deflate = strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate');
      // Determine used compression method
      $encoding = $gzip ? 'gzip' : ($deflate ? 'deflate' : 'none');
      // Check for buggy versions of Internet Explorer
      if (!strstr($_SERVER['HTTP_USER_AGENT'], 'Opera') && 
        preg_match('/^Mozilla\/4\.0 \(compatible; MSIE ([0-9]\.[0-9])/i', $_SERVER['HTTP_USER_AGENT'], $matches)) {
        $version = floatval($matches[1]);
        if ($version < 6)
          $encoding = 'none';
        if ($version == 6 && !strstr($_SERVER['HTTP_USER_AGENT'], 'EV1')) 
          $encoding = 'none';
      }
      // Try the cache first to see if the combined files were already generated
      $cachefile = 'cache-' . $hash . '.' . $file_type . ($encoding != 'none' ? '.' . $encoding : '');
      if (file_exists($cachedir . '/' . $cachefile)) {
        if ($fp = fopen($cachedir . '/' . $cachefile, 'rb')) {
          if ($encoding != 'none') {
            header ("Content-Encoding: " . $encoding);
          }
          header ("Content-Type: text/" . $file_type);
          header ("Content-Length: " . filesize($cachedir . '/' . $cachefile));
          fpassthru($fp);
          fclose($fp);
          exit;
        }
      }
    }
    // Get contents of the files
    $contents = '';
    reset($elements);
    while (list(,$element) = each($elements)) {
      $path = $base . '/' . $element;
      $contents .= "\n\n" . file_get_contents($path);
    }
    // Send Content-Type
    header ("Content-Type: text/" . $file_type);
    if (isset($encoding) && $encoding != 'none') 
    {
      // Send compressed contents
      $contents = gzencode($contents, 9, $gzip ? FORCE_GZIP : FORCE_DEFLATE);
      header ("Content-Encoding: " . $encoding);
      header ('Content-Length: ' . strlen($contents));
      echo $contents;
    } 
    else
    {
      // Send regular contents
      header ('Content-Length: ' . strlen($contents));
      echo $contents;
    }
    // Store cache
    if ($cache) {
      if ($fp = fopen($cachedir . '/' . $cachefile, 'wb')) {
        fwrite($fp, $contents);
        fclose($fp);
      }
    }
  }

希望本文所述对大家的php程序设计有所帮助。

PHP 相关文章推荐
其他功能
Oct 09 PHP
功能齐全的PHP发送邮件类代码附详细说明
Jul 10 PHP
PHP 强制下载文件代码
Oct 24 PHP
php中根据某年第几天计算出日期年月日的代码
Feb 24 PHP
PHP判断图片格式的七种方法小结
Jun 03 PHP
smarty中js的调用方法示例
Oct 27 PHP
php判断输入是否是纯数字,英文,汉字的方法
Mar 05 PHP
php数组索引与键值操作技巧实例分析
Jun 24 PHP
PHP命令Command模式用法实例分析
Aug 08 PHP
Yii2.0框架模型多表关联查询示例
Jul 18 PHP
PHP 面向对象程序设计之类属性与类常量实现方法分析
Apr 13 PHP
Laravel6.18.19如何优雅的切换发件账户
Jun 14 PHP
PHP实现加强版加密解密类实例
Jul 29 #PHP
PHP之密码加密的几种方式
Jul 29 #PHP
PHP实现仿Google分页效果的分页函数
Jul 29 #PHP
PHP如何将log信息写入服务器中的log文件
Jul 29 #PHP
再Docker中架设完整的WordPress站点全攻略
Jul 29 #PHP
php去掉文件前几行的方法
Jul 29 #PHP
PHP实现的简单网络硬盘
Jul 29 #PHP
You might like
php 8小时时间差的解决方法小结
2009/12/22 PHP
mysql下创建字段并设置主键的php代码
2010/05/16 PHP
写出高质量的PHP程序
2012/02/04 PHP
php使用正则表达式进行字符串搜索的方法
2015/03/23 PHP
实例简介PHP的一些高级面向对象编程的特性
2015/11/27 PHP
javascript下给元素添加事件的方法与代码
2007/08/13 Javascript
Json字符串转换为JS对象的高效方法实例
2013/05/01 Javascript
jQuery实现回车键(Enter)切换文本框焦点的代码实例
2014/05/05 Javascript
javascript基于HTML5 canvas制作画箭头组件
2014/06/25 Javascript
深入剖析JavaScript编程中的对象概念
2015/10/21 Javascript
AngularJS实现全选反选功能
2015/12/08 Javascript
JavaScript常用基础知识强化学习
2015/12/09 Javascript
使用JSON作为函数的参数的优缺点
2016/10/27 Javascript
angular中的http拦截器Interceptors的实现
2017/02/21 Javascript
浅析Vue 生命周期
2018/06/21 Javascript
微信小程序实现图片滚动效果示例
2018/12/05 Javascript
JavaScript使用小插件实现倒计时的方法讲解
2019/03/11 Javascript
Tornado Web服务器多进程启动的2个方法
2014/08/04 Python
python使用线程封装的一个简单定时器类实例
2015/05/16 Python
python安装cx_Oracle模块常见问题与解决方法
2017/02/21 Python
python执行系统命令后获取返回值的几种方式集合
2018/05/12 Python
Python获取统计自己的qq群成员信息的方法
2019/11/15 Python
Python之——生成动态路由轨迹图的实例
2019/11/22 Python
Pytorch实现LSTM和GRU示例
2020/01/14 Python
浅谈keras的深度模型训练过程及结果记录方式
2020/01/24 Python
Python while循环使用else语句代码实例
2020/02/07 Python
jupyter notebook读取/导出文件/图片实例
2020/04/16 Python
使用Pycharm在运行过程中,查看每个变量的操作(show variables)
2020/06/08 Python
css3实现平移效果(transfrom:translate)的示例
2020/11/13 HTML / CSS
澳大利亚拥有最佳跳伞降落点和最好服务的跳伞项目运营商:Skydive Australia
2018/03/05 全球购物
洛佩桑酒店官方网站:Lopesan Hotels
2019/04/15 全球购物
《长城和运河》教学反思
2014/04/14 职场文书
员工教育培训协议书
2014/09/27 职场文书
教师群众路线教育实践活动个人对照检查材料
2014/11/04 职场文书
通用员工手册范本
2015/05/14 职场文书
使用ORM新增数据在Mysql中的操作步骤
2021/07/26 MySQL