Home Backend Development PHP Tutorial Example of php gzip compressing js and css code

Example of php gzip compressing js and css code

Jul 25, 2016 am 08:59 AM

In order to save bandwidth, we often need to compress files before transmitting them. In PHP programming, the most common method is to use the gzip module to compress CSS and JS files. This article gives you an example in this regard for your reference.

First, let’s understand the advantages of compression: 1) Merge multiple CSS/JS documents into one file to reduce HTTP requests. 2) Perform document compression on the merged files, such as using js compressor and CSS compress respectively. 3) If you use some mainstream JavaScript frameworks, such as JQuery, Mootools or YUI, it is strongly recommended to directly use Google AJAX Library to import the base library in the form of external links. 4) Use GZIP to compress JS/CSS documents on the server side.

Using GZIP compression with PHP is very simple, the core of which is to use ob_gzhandler. Note: Not all browsers support GZIP data transmitted to the client, fault tolerance must be considered. Let me give you an example of PHP compressing CSS through GZIP. In the folder where the CSS is stored, create a new style.php file. File style.php:

<?php
if(extension_loaded('zlib')){//检查是否开启zlib
 ob_start('ob_gzhandler');
}
header('content-type: text/css; charset: gb2312');//编码,可修改
header('cache-control: must-revalidate');
$offset = 60 * 60 * 24;//css文件的距离现在的过期时间,这里设置为一天
$expire = 'expires: ' . gmdate('D, d M Y H:i:s', time() + $offset) . ' GMT';
header($expire);
ob_start('compress');
function compress($buffer) {//去除文件中的注释
 $buffer = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $buffer);
 return $buffer;
}
//包含你的全部css文档
include('global.css');
include('layout.css');
if(extension_loaded('zlib')){
 ob_end_flush();//输出buffer中的内容,即压缩后的css文件
}
?>
Copy after login

The above code is only used to compress CSS files. If you need to compress JavaScript files, change the Content-type in line 5 of the above code to:

header('content-type:application/x-javascript; charset: gb2312');
Copy after login

At the same time, pay attention to the encoding of the file. The encoding used here is gb2312. If you use UTF-8 or other encoding, just change it to the corresponding one (i.e. utf-8). After the modification is completed, introduce the relevant required CSS files, and then replace the place where the CSS is introduced in the original HTML with the following introduction method:

<link rel="stylesheet" media="screen" href="style/css.php?v=100415" />
Copy after login

Similarly, the way to introduce JS is as follows:


Copy after login

Since the above code uses the Expires attribute of HTTP to cache CSS/JS code on the client side, if the expiration time is set too long (such as one year), when you modify JS/css on the server side code, the client may not take effect immediately. Solution: Add a random parameter after the php file, such as v=121 in the above example. When the file is modified next time, remember to modify this random parameter accordingly (for example, change it to 122).

That’s it. I hope you can test it yourself and see if there will be a big improvement in the website access speed before and after compression! Programmer's Home, I wish you all to make progress in your studies and make progress every day! !



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles