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 相关文章推荐
php数据库配置文件一般做法分享
Jul 07 PHP
实测在class的function中include的文件中非php的global全局环境
Jul 15 PHP
php下pdo的mysql事务处理用法实例
Dec 27 PHP
使用php从身份证号中获取一系列线索(星座、生肖、生日等)
May 11 PHP
Yii2框架使用计划任务的方法
May 25 PHP
php 获取文件行数的方法总结
Oct 11 PHP
php函数mkdir实现递归创建层级目录
Oct 27 PHP
PC端微信扫码支付成功之后自动跳转php版代码
Jul 07 PHP
php脚本守护进程原理与实现方法详解
Jul 20 PHP
php中输出json对象的值(实现方法)
Mar 07 PHP
基于ThinkPHP5框架使用QueryList爬取并存入mysql数据库操作示例
May 25 PHP
php DES加密算法实例分析
Sep 18 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
深入了解php4(1)--回到未来
2006/10/09 PHP
php与java通过socket通信的实现代码
2013/10/21 PHP
thinkPHP3.2简单实现文件上传的方法
2016/05/16 PHP
php UNIX时间戳用法详解
2017/02/16 PHP
Javascript-Mozilla和IE中的一个函数直接量的问题分析
2007/08/12 Javascript
JS 日期验证正则附asp日期格式化函数
2009/09/11 Javascript
使用jQuery简化Ajax开发 Ajax开发入门
2009/10/14 Javascript
js getBoundingClientRect() 来获取页面元素的位置
2010/11/25 Javascript
理解JSON:3分钟课程
2011/10/28 Javascript
JavaScript prototype 使用介绍
2013/08/29 Javascript
探讨js中的双感叹号判断
2013/11/11 Javascript
jQuery 中国省市两级联动选择附图
2014/05/14 Javascript
jqueryUI里拖拽排序示例分析
2015/02/26 Javascript
angular ngClick阻止冒泡使用默认行为的方法
2016/11/03 Javascript
微信小程序实现长按删除图片的示例
2018/05/18 Javascript
vue修改对象的属性值后页面不重新渲染的实例
2018/08/09 Javascript
微信小程序实现页面下拉刷新和上拉加载功能详解
2018/12/03 Javascript
Python中的True,False条件判断实例分析
2015/01/12 Python
Python虚拟环境Virtualenv使用教程
2015/05/18 Python
黑科技 Python脚本帮你找出微信上删除你好友的人
2016/01/07 Python
Python的爬虫程序编写框架Scrapy入门学习教程
2016/07/02 Python
Python实现简单查找最长子串功能示例
2019/02/26 Python
python 安装库几种方法之cmd,anaconda,pycharm详解
2020/04/08 Python
html+css实现自定义图片上传按钮功能
2019/09/04 HTML / CSS
Woods官网:加拿大最古老、最受尊敬的户外品牌之一
2020/09/12 全球购物
什么是用户模式(User Mode)与内核模式(Kernel Mode) ?
2015/09/07 面试题
大学生个人求职信范文
2013/09/21 职场文书
新闻网站实习自我鉴定
2013/09/25 职场文书
销售总监工作职责
2013/11/21 职场文书
班级学习计划书
2014/04/27 职场文书
支行行长竞聘演讲稿
2014/05/15 职场文书
结婚喜宴迎宾词
2015/08/10 职场文书
诚实守信主题班会
2015/08/13 职场文书
素质教育学习心得体会
2016/01/19 职场文书
2016年安全月活动总结
2016/04/06 职场文书
Python快速实现一键抠图功能的全过程
2021/06/29 Python