Home >Backend Development >PHP Tutorial >Resolving doubts about PHP's ob_start() function_PHP tutorial
php ob_start and ob_end_flush() are php’s buffered output functions.
ob_start([string output_callback])- Open the output buffer. All output information is no longer sent directly to the browser, but is saved in the output buffer. The optional callback function is used to process the output result information.
ob_end_flush - End (send) the contents of the output buffer, closing the output buffer.
What PHP outputs will be saved in a memory maintained by PHP. It can be called buffer or cache, which all mean the same thing. Then when the buffer is full, php will automatically send the data to the web server.
That is to say, every echo will not necessarily output something, but will be saved in the buffer.
The meaning of ob_start() can be understood as (but it is actually different from what I say below). This buffer is controlled by the ob_ series of functions. That is, PHP will not maintain its own buffer and will not automatically The contents of the buffer are automatically sent to the web server until you ob_end() or similar ob operation.
The ob_ function is generally used to capture the current output and has nothing to do with efficiency. As for why the output is captured, there are many reasons. For example, if I capture the output and cache it in a file, the next request can directly read the contents of this cache file as output.
ob_start(); 内容 echo ob_get_contents() ;
It’s code like the above. To put it bluntly, it has no meaning.
After I thought about it carefully, I searched online and found that quite a few beginners (technical beginners, not necessarily first-year PHP students, some people have been beginners their entire lives) do not understand the role of ob. , but ob is often called output buffer and output cache on the Internet, so many people regard the ob series functions as tools to speed up PHP page display.
In fact, ob is the abbreviation of output buffering, not output cache. If ob is used correctly, it can help the speed to a certain extent, but blindly adding the ob function will only increase the extra burden on the CPU. Next I will talk about the basic function of ob.
Regarding the GZIP compression mentioned in the third point just mentioned, many people may want to use it, but have not really used it. In fact, by slightly modifying my friend's code, you can achieve gzip compression of the page.
ob_start(ob_gzhandler); 内容
Yes, just add a callback function ob_gzhandler, but there are some minor problems with this. First, it requires zlib support, and second, it does not determine whether the browser supports gzip (it seems to support it now, and iPhone browsers seem to support it) ).
The previous approach was to determine whether the browser supports gzip, then use the third-party gzip function to compress the content of ob_get_contents(), and finally echo.