Home php教程 php手册 PHP输出缓存ob系列函数详解

PHP输出缓存ob系列函数详解

Jun 06, 2016 pm 08:24 PM
php

ob,输出缓冲区,是output buffering的简称,而不是output cache。ob用对了,是能对速度有一定的帮助,但是盲目的加上ob函数,只会增加CPU额外的负担

ob的基本原则:如果ob缓存打开,则echo的数据首先放在ob缓存。如果是header信息,直接放在程序缓存。当页面执行到最后,会把ob缓存的数据放到程序缓存,然后依次返回给浏览器。
下面我说说ob的基本作用:
  1)防止在浏览器有输出之后再使用setcookie()、header()或session_start()等发送头文件的函数造成的错误。其实这样的用法少用为好,养成良好的代码习惯。
  2)捕捉对一些不可获取的函数的输出,比如phpinfo()会输出一大堆的HTML,但是我们无法用一个变量例如$info=phpinfo();来捕捉,这时候ob就管用了。
  3)对输出的内容进行处理,例如进行gzip压缩,例如进行简繁转换,例如进行一些字符串替换。
  4)生成静态文件,其实就是捕捉整页的输出,然后存成文件。经常在生成HTML,或者整页缓存中使用。

对于刚才说的第三点中的GZIP压缩,可能是很多人想用,却没有真用上的,其实稍稍修改下代码,就可以实现页面的gzip压缩。

复制代码 代码如下:

ob_start(ob_gzhandler);
要缓存的内容


没错,加一个ob_gzhandler这个回调函数就可以了,不过这么做有些小问题,一是需要zlib支持,二是没有判断浏览器是否支持gzip(现在好像都支持,iphone浏览器好像都支持了)。
以前的做法是判断一下浏览器是否支持gzip,然后用第三方的gzip函数来压缩ob_get_contents() 的内容,最后echo。

一、ob系列函数中常用函数集锦

复制代码 代码如下:


ob_start();            //打开一个输出缓冲区,所有的输出信息不再直接发送到浏览器,而是保存在输出缓冲区里面。

ob_clean();            //删除内部缓冲区的内容,不关闭缓冲区(不输出)。
ob_end_clean();        //删除内部缓冲区的内容,关闭缓冲区(不输出)。
ob_get_clean();        //返回内部缓冲区的内容,关闭缓冲区。相当于执行 ob_get_contents() and ob_end_clean()
ob_flush();            //发送内部缓冲区的内容到浏览器,删除缓冲区的内容,不关闭缓冲区。
ob_end_flush();        //发送内部缓冲区的内容到浏览器,删除缓冲区的内容,关闭缓冲区。
ob_get_flush();        //返回内部缓冲区的内容,并关闭缓冲区,再释放缓冲区的内容。相当于ob_end_flush()并返回缓冲区内容。
flush();               //将ob_flush释放出来的内容,以及不在PHP缓冲区中的内容,全部输出至浏览器;刷新内部缓冲区的内容,并输出。

ob_get_contents();     //返回缓冲区的内容,不输出。
ob_get_length();       //返回内部缓冲区的长度,如果缓冲区未被激活,该函数返回FALSE。
ob_get_level();        //Return the nesting level of the output buffering mechanism.
ob_get_status();       //Get status of output buffers.

ob_implicit_flush();   //打开或关闭绝对刷新,默认为关闭,打开后ob_implicit_flush(true),所谓绝对刷新,即当有输出语句(e.g: echo)被执行时,便把输出直接发送到浏览器,而不再需要调用flush()或等到脚本结束时才输出。

ob_gzhandler               //ob_start回调函数,用gzip压缩缓冲区的内容。
ob_list_handlers           //List all output handlers in use
output_add_rewrite_var     //Add URL rewriter values
output_reset_rewrite_vars  //Reset URL rewriter values

这些函数的行为受php_ini设置的影响:
output_buffering       //该值为ON时,将在所有脚本中使用输出控制;若该值为一个数字,则代表缓冲区的最大字节限制,当缓存内容达到该上限时将会自动向浏览器输出当前的缓冲区里的内容。
output_handler         //该选项可将脚本所有的输出,重定向到一个函数。例如,将 output_handler 设置为 mb_output_handler() 时,字符的编码将被修改为指定的编码。设置的任何处理函数,将自动的处理输出缓冲。
implicit_flush         //作用同ob_implicit_flush,默认为Off。

二、实例讲解

1、使 header() 函数前可以有echo代码
Output Control 函数可以让你自由控制脚本中数据的输出。它非常地有用,特别是对于:当你想在数据已经输出后,再输出文件头的情况。
输出控制函数不对使用 header() 或 setcookie(),发送的文件头信息产生影响,只对那些类似于 echo() 和 PHP 代码的数据块有作用。 

复制代码 代码如下:

ob_start();                   //打开缓冲区 
echo "Hello\n";               //输出 
header(“location:index.php”); //把浏览器重定向到index.php  
ob_end_flush();               //输出全部内容到浏览器


所有对header()函数有了解的人都知道,这个函数会发送一段文件头给浏览器,但是如果在使用这个函数之前已经有了任何输出(包括空输出,比如空格,回车和换行)就会提示出错。如果我们去掉第一行的ob_start(),再执行此程序,我们会发现得到了一条错误提示:"Header had all ready send by"!但是加上ob_start,就不会提示出错,原因是当打开了缓冲区,echo后面的字符不会输出到浏览器,而是保留在服务器,直到你使用flush或者ob_end_flush才会输出,所以并不会有任何文件头输出的错误!
2、保存 phpinfo() 函数的输出

复制代码 代码如下:

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

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.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles