Php ob_start (ob_gzhandler) for web page Compression

Source: Internet
Author: User

This article will summarize the implementation of php ob_start (ob_gzhandler) for web page compression and transmission. If you need it, please refer to it.

First, let's look at the usage of ob_start.

Use the PHP ob_start () function to open the browser cache. This ensures that the cache content will not be output before you call flush (), ob_end_flush () (or after the program is executed ).

The Code is as follows: Copy code

<? Php

Ob_start (); // open the buffer
Phpinfo (); // use the phpinfo Function
$ Info = ob_get_contents (); // obtain the buffer content and assign it to $ info
Using file1_fopen('info.txt ', 'w'); // open the info.txt file.
Fwrite ($ file, $ info); // write the information to info.txt
Fclose ($ file); // close the info.txt file

?>

PHP ob_start () functions have a great feature. You can also use the ob_start parameter to automatically run commands after the cache is written, such as ob_start ("ob_gzhandler "); the most common practice is to use ob_get_contents () to get the content in the cache.

The code below is an example of compressing a webpage. We use the ob_gzip function to compress the output content with ob_start and put it in the "buffer zone" before outputting it.

The Code is as follows: Copy code

// Enable Compression
If (function_exists ('ob _ gzip '))
{
Ob_start ('ob _ gzip ');
}
// Prepare some content to be compressed
For ($ I = 0; I I <100; $ I ++)
{
Echo ('here is the test content <br> ');
}
// Output compressed results
Ob_end_flush ();


// This is the ob_gzip compression function.
Function ob_gzip ($ content)
{
If (! Headers_sent () & extension_loaded ("zlib") & strstr ($ _ SERVER ["HTTP_ACCEPT_ENCODING"], "gzip ")){
$ Content = gzencode ($ content, 9 );
Header ("Content-Encoding: gzip ");
Header ("Vary: Accept-Encoding ");
Header ("Content-Length:". strlen ($ content ));
}
Return ($ content );
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.