SoFunction
Updated on 2025-03-03

PHP using gzip to compress the method of transmitting js and css files

PHP using gzip to compress the method of transmitting js and css files

Updated: July 29, 2015 11:04:28 Author: DDIAN
This article mainly introduces the method of using gzip to compress the JS and CSS files. It analyzes the relevant skills of using gzip to compress JS and CSS files. It has certain reference value. Friends who need it can refer to it.

This article describes the method of using gzip to compress the JS and CSS files. Share it for your reference. The details are as follows:

<?php
  /**
    * Complete call example:
    * 1. ?t=j&b=public&fs=,function
    *
    * This example calls public/jslib/ and public/ in the root directory of the website
    *
    * 2. ?t=j&fs=,function
    *
    * This example calls jslib/ and
    *
    * 3. ?t=c&b=&fs=common,index
    *
    * This example calls public/css/ and public/css/ in the root directory of the website
    *
    * 4. ?t=c&fs=
    * This example calls css/ in the root directory of the website
    *
    * Note: Use multiple file names to separate them; only one file name should not be included at the end.
    * Use, multiple separated files will be compressed into one file and passed to the browser at one time.
    **/
  $is_bad_request=false;
  $cache = true;
  $doc_root_uri=$_SERVER['DOCUMENT_ROOT'].'/';
  $cachedir = $doc_root_uri . 'public/cache';
  //File type, j is js, c is css  $type=isset($_GET['t'])?($_GET['t']=='j'||$_GET['t']=='c'?$_GET['t']:''):'';
  //The base directory for storing js and css files, for example: ?b= represents the /public/js folder, and the starting point is the website root directory  //Base directory parameters are not required. If there is a base directory, then this base directory will be appended before the file name  $base =isset($_GET['b'])?($doc_root_uri.str_replace('.','/',$_GET['b'])):$doc_root_uri;
  //File name list, file name without suffix name. For example, the base directory is  //The format of the file name is: base directory (if any) + file package name + file name  //For example: type is j,  //   file name  // If there is a base path and it is public,  // Then the converted file name is /public/public/js/  // If there is no base path  // Then the converted file name is /public/js/  // Use multiple file names to separate  $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);
      }
    }
  }

I hope this article will be helpful to everyone's PHP programming.

  • php
  • gzip
  • js
  • css

Related Articles

  • Detailed explanation of using memcache to store session based on php

    This article provides a detailed analysis and introduction to the use of memcache storage session of php. For those who need it, please refer to it.
    2013-06-06
  • Example of simple mine-sweeping game implemented by php

    This article mainly introduces the simple mine-sweeping game implemented by PHP, involving related techniques for PHP strings and process control, and has certain reference value. Friends who need it can refer to it.
    2015-07-07
  • PHP array sorting function collection and analysis of their connections

    This article provides a detailed analysis and introduction to the PHP array sorting function collection and the connection between them. For those who need it, please refer to it.
    2013-06-06
  • Complete example of XML operation (read) encapsulation class implemented by php

    This article mainly introduces the XML operation (read) encapsulation class implemented by php, gives an example of xml format file, and analyzes the relevant operation techniques of php traversing and reading xml format data nodes in combination with the complete example form. Friends who need it can refer to it
    2017-02-02
  • php uses array_search function to implement array search method

    This article mainly introduces the method of using the array_search function to implement array search, which involves related skills of php array search. Friends who need it can refer to it
    2015-06-06
  • Several methods for php to calculate the length of Chinese and English strings

    This article mainly introduces several methods to calculate the length of Chinese and English strings using php. There are detailed code examples for your reference, which are of certain reference value for your study or work. Friends who need it can refer to it.
    2023-11-11
  • Examples of text watermarks, thumbnails, and image watermark implementation classes and usage methods developed by PHP

    This article mainly introduces the implementation classes and usage of text watermarks, thumbnails, and image watermarks developed by PHP. It analyzes the definitions and simple usage of php text watermarks, thumbnails operation classes based on the complete example form. Friends who need it can refer to it.
    2019-04-04
  • Explanation of examples of escaped into special characters in php strings

    In this article, the editor will share with you an example explanation about the escape of special characters in php strings. Friends who are interested in this can learn it.
    2021-02-02
  • Code to download pictures in CSS files using PHP

    I didn't know how to download the pictures in the CSS file before, but now I can use php to implement them simply. The details are as follows. Interested friends can refer to them.
    2013-09-09
  • Time display in php

    Time display in php...
    2007-01-01

Latest Comments