search
HomeBackend DevelopmentPHP TutorialPHP controls page browser cache and enables gzip transmission_PHP tutorial

PHP controls page browser cache and enables gzip transmission_PHP tutorial

Jul 13, 2016 am 10:50 AM
gzipphpandintroducetransmitclassmateenablecontrolarticleBrowsercachepage

This article will introduce to you how to control page browser caching in PHP and enable gzip page transmission. I hope this code will be helpful to you. At the same time, friends who do not have server permissions can implement server gzip page transmission in this way.

php instance gzip transfer page

The code is as follows Copy code
 代码如下 复制代码

可以用于静态资源与html页面,修改一下也适合于其他语言

//缓存过期时间(Cache-Control, http1.1协义), 推荐使用
$secs = 0; //秒
header("Cache-Control: s-maxage=$secs, max-age=$secs, must-revalidate, proxy-revalidate");

// 缓存过期时间为24小时(Expires)
$offset = 3600 * 24;
$expire = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
Header($expire); 

//Last-Modified, 最后修改的时间
$gmt_mtime = gmdate('D, d M Y H:i:s', time() ) . ' GMT';
header("Last-Modified: " . $gmt_mtime );   

//启用gzip压缩
ob_start();
    ... your php code ...
    ... your php code ...
    ... your php code ...
    header('Content-Length: ' . ob_get_length());
ob_end_flush();   

Can be used for static resources and html pages, and can be adapted to other languages ​​if modified

//Cache expiration time (Cache-Control, http1.1 protocol), recommended to use $secs = 0; //Seconds

header("Cache-Control: s-maxage=$secs, max-age=$secs, must-revalidate, proxy-revalidate");


//The cache expiration time is 24 hours (Expires)

$offset = 3600 * 24;

$expire = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";

Header($expire);

//Last-Modified, the time of the last modification

$gmt_mtime = gmdate('D, d M Y H:i:s', time() ) . ' GMT';

header("Last-Modified: " . $gmt_mtime );
 代码如下 复制代码


SetOutputFilter DEFLATE
DeflateCompressionLevel 5
AddOutputFilterByType DEFLATE text/html text/css image/gif image/jpeg image/png application/x-javascript

//Enable gzip compression ob_start(); ... your php code ... ... your php code ... ... your php code ... header('Content-Length: ' . ob_get_length()); ob_end_flush();
If you have server permissions, you can refer to apache to enable gzip transmission 1. Find your httpd.conf file, open it and find the following LoadModule deflate_module modules/mod_deflate.so Remove the # in front, because the mod_deflate.so module is closed by default, here’s what’s next Two, just put the current code at the end of your httpd.conf file.
The code is as follows Copy code
SetOutputFilter DEFLATE DeflateCompressionLevel 5 AddOutputFilterByType DEFLATE text/html text/css image/gif image/jpeg image/png application/x-javascript

Restart your apache and it will be KO

iis enables gzip page transfer

1. Open Internet Information Services (IIS) Manager, right-click "Website" -> "Properties" and select "Services". Select "Compress Application Files" and "Compress Static Files" in the "HTTP Compression" box, and set the "Temporary Directory" and "Maximum Limit of Temporary Directory" as needed;

2. In the Internet Information Services (IIS) Manager, right-click "Web Service Extensions" - "Add a new Web Service Extension..." and enter the extension name in the "New Web Service Extension" box. HTTP Compression", add the "Required File" as C:WINDOWSsystem32inetsrvgzip.dll, where the Windows system directory may be different depending on your installation, check "Set extension status to Allow";

3. Use a text editor to open C:WindowsSystem32inetsrvMetaBase.xml (it is recommended to back up first),

Find Location="/LM/W3SVC/Filters/Compression/gzip to set gzip compression,

Find Location="/LM/W3SVC/Filters/Compression/deflate" to set deflate compression. The two nodes above are next to each other. And the properties set are the same.

If you need to compress dynamic files, set HcDoDynamicCompression to "TRUE",

And add the dynamic file suffix you want to compress in HcScriptFileExtensions, such as aspx;

If static files need to be compressed, set HcDoStaticCompression and HcDoOnDemandCompression to "TRUE",

And add the suffix name of the static file you need to compress in HcFileExtensions, such as xml, css, etc.;

HcDynamicCompressionLevel and HcOnDemandCompLevel represent the required compression rate, the value is 0-10, and the default is 0.

HcDynamicCompressionLevel property description: HcDynamicCompressionLevel Metabase Property

HcOnDemandCompLevel property description: HcOnDemandCompLevel Metabase Property

Note: It is generally recommended to set the value of these two attributes to 9, which has the best cost performance.

Attention

1. You need to stop IIS before editing MetaBase.xml. You can use net stop iisadmin

2. After the modification is completed, start the iisadmin service and execute the iisreset command

About SEO testing

Whether compression has any impact on SEO? After testing, it can still be well included after being turned on.

For research articles on the impact on SEO, you can also refer to the following articles.

Specific efficiency issues will continue to be monitored for research

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632650.htmlTechArticleThis article will introduce to you the methods of controlling php page browser cache and enabling gzip to transmit pages. I hope this code will help This will be helpful to everyone. Friends who do not have server permissions can...
Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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 Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools