Use PHP to control the user's browser -- instructions for using the ob * function _ PHP Tutorial

Source: Internet
Author: User
Use PHP to control the use of the user's browser-ob * function. Using PHP to control the user's browser -- ob * function using OutputControl function allows you to freely control the data output in the script. It is very useful, especially for: when you want
Use PHP to control the use of the user's browser-ob * function

The Output Control function allows you to freely Control the Output of data in the script. It is very useful, especially when you want to output the file header after the data has been output. The output control function does not affect the header information sent using header () or setcookie (). it only applies to data blocks similar to echo () and PHP code.

Let's take a simple example to give you a general impression on Output Control:
Example 1.

Ob_start (); // open the buffer
Echo "Hellon"; // output
Header ("location: index. php"); // redirects the browser to index. php.
Ob_end_flush (); // output all content to the browser
?>


Anyone who knows about the header () function knows that this function will send a file header to the browser, but if any output (including null output, for example, a blank space, carriage return, or line feed will prompt an error. If we remove ob_start () from the first line and execute this program, we will find an error message: "Header had all ready send "! However, when ob_start is added, no error will be prompted because when the buffer zone is opened, the characters after echo will not be output to the browser, but will be retained on the server until you use flush or ob_end_flush, so there will be no file header output errors!

1. related functions
1. Flush: refresh the buffer content and output it.
Function format: flush ()
Note: This function is frequently used and highly efficient.

2. ob_start: Open the output buffer.
Function format: void ob_start (void)
Note: When the buffer zone is activated, all non-file header information from the PHP program is not sent, but stored in the internal buffer zone. To output the buffer content, you can use ob_end_flush () or flush () to output the buffer content.

3. ob_get_contents: returns the content of the internal buffer.
Usage: string ob_get_contents (void)
Note: This function returns the content in the current buffer. if the output buffer is not activated, FALSE is returned.

4. ob_get_length: return the length of the internal buffer.
Usage: int ob_get_length (void)
Note: This function returns the length of the current buffer. it is the same as ob_get_contents if the output buffer is not activated. Returns FALSE.

5. ob_end_flush: sends the content of the internal buffer to the browser and closes the output buffer.
Usage: void ob_end_flush (void)
Note: This function sends the content of the output buffer (if any ).

6. ob_end_clean: delete the content of the internal buffer and disable the internal buffer.
Usage: void ob_end_clean (void)
Note: This function will not output the content of the internal buffer but delete it!

7. ob_implicit_flush: enable or disable absolute refresh
Usage: void ob_implicit_flush ([int flag])
Note: Anyone who has used Perl knows the meaning of $ | = x. This string can enable/disable the buffer, while the ob_implicit_flush function is the same as that. the buffer is disabled by default, after the absolute output is enabled, each script output is directly sent to the browser, and you do not need to call flush ()

2. In-depth understanding

1. about the Flush function:
This function appears in PHP3. it is a very efficient function. a very useful function is to refresh the browser cache. we will give an example with very obvious running effect to illustrate flush.
Example 2.

For ($ I = 1; $ I <= 300; $ I ++) print ("");
// This sentence is critical. the cache structure makes it output from the browser only when the content reaches a certain size.
// In other words, if the cache content does not reach a certain size, it will not be output before the program is executed. Jing
// After testing, I found that the base size is 256 characters long. This means that all content received by the cache will be
// Continuously sent out.
For ($ j = 1; $ j <= 20; $ j ++ ){
Echo $ j ."
";
Flush (); // This part will squeeze out the new content of the cache and display it on the browser.
Sleep (1); // let the program "sleep" for one second, so that you can see the effect more clearly
}

?>

The specific effect you can look at here http://www.php2000.com /~ Uchinaboy/out. php
PHP2000's latest PHP chat room uses this technology. Unfortunately, the source code is not public.
Note: If you add ob_implicit_flush () to the program header to enable absolute refresh, you can stop using flush () in the program. The advantage of doing this is to improve efficiency!


2. ob functions:
I would like to first reference an example of my good friend y10k:
Example 3.
For example, you can obtain the configuration information of the server and the client, but this information may vary depending on the client. what if you want to save the output of the phpinfo () function? There is no way to control the buffer, but with the control of the buffer, we can easily solve the problem:

Ob_start (); // open the buffer
Phpinfo (); // use the phpinfo function
$ Info = ob_get_contents (); // Obtain the buffer content and assign it to $ info
$ File = 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

?>

With the above method, you can save the phpinfo information of different users. I am afraid there is no way to do this before! In fact, the above is how to convert some "procedures" into "functions!
Someone may ask, "is it like this? Is there any other purpose ?" Of course, for example, the PHP syntax highlighted by the Author Forum is related to this (the default PHP syntax highlighted by the display function will be directly output and the results cannot be saved, I am afraid it will be a waste of CPU if it is displayed in every call. in my forum, I will keep the result of the function highlighted by the syntax in the method of controlling the buffer ), if you are interested, you can take a look at the http://www.zphp.com/bbs!

You may have some knowledge about the functions of ob_start (). the above example seems simple, but you have mastered the key points of using ob_start.
<1> use ob_start 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.
<2>. now you should know your advantages: you can use header, setcookie, and session after any output content, which is a great feature of ob_start. you can also use the ob_start parameter, after the cache is written, run the command automatically, such as ob_start ("ob_gzhandler"). The most common practice is to use ob_get_contents () to get the content in the cache, and then proceed ......
<3>. after processing is completed, we can use various methods for output, flush (), ob_end_flush (), and automatic output after the program is executed. Of course, if you use ob_get_contents (), you can control the output mode by yourself.

Let's see what we can do with ob functions ......


(1) Static template technology

Introduction: the static template technology allows users to obtain html pages generated by PHP on the client side in some way. If this html page is no longer updated, when another user browses this page again, the program will no longer call PHP and related databases. for some websites with a large amount of information, for example, sina, 163, sohu. The benefits of similar technologies are enormous.

I know there are two ways to implement static output:
<1>. use the template. inc. php class modified by y10k to implement phplib.
<2>. use ob functions.
For the first method, because it is not a problem to be studied in this article, I will not go into details.
Let's take a look at the specific implementation of the second method:
Example 4.

Ob_start (); // open the buffer
?>


All php page output

$ Content = ob_get_contents (); // retrieves all the content output on the php page.
$ Fp = fopen ("output00001. html", "w"); // create a file, open it, and write
Fwrite ($ fp, $ content); // write the content of the PHP page into output00001.html, and then ......
Fclose ($ fp );
?>


In this way, the so-called static templates can be easily implemented ......

(2) capture output

The above Example 4 is the simplest case. you can operate $ content before writing ......
You can try to capture some keywords and then process them, such as the PHP syntax highlighted in Example 3. I personally think that this function is the biggest essence of this function. it can solve a variety of problems, but you need to have enough imagination ......
Example 5.

Function run_code ($ code ){
If ($ code ){
Ob_start ();
Eval ($ code );
$ Contents = ob_get_contents ();
Ob_end_clean ();
} Else {
Echo "error! No output ";
Exit ();
}
Return $ contents;
}

?>

The above example is not very useful, but the typical $ code itself is an output page containing variables, and this example uses eval to replace the variables in $ code, then capture the output results and process them again ......

Example 6. faster transmission

/*
** Title ......: PHP4 HTTP Compression Speeds up the Web
** Version ......: 1.20
** Author ......: catoc
** Filename...: gzdoc. php
** Last changed...: 18/10/2000
** Requirments...: PHP4> = 4.0.1
** PHP was configured with -- with-zlib [= DIR]
** Notes...: Dynamic Content Acceleration compresses
** The data transmission data on the fly
** Code by sun jin hu (catoc)
** Most newer browsers since 1998/1999 have
** Been equipped to support the HTTP 1.1
** Standard known as "content-encoding ."
** Essentially the browser indicates to
** Server that it can accept "content encoding"
** And if the server is capable it will then
** Compress the data and transmit it.
** Browser decompresses it and then renders
** The page.
**
** Modified by John Lim (jlim@natsoft.com.my)
** Based on ideas by Sandy McArthur, Jr
** Usage ........:
** No space before the beginning of the first' ** ------------ Start of file ----------
** | ** | Include ('gzdoc. php ');
** |? >
** |
** |... The page...
** |
** | ** | Gzdocout ();
** |? >
** ------------- End of file -----------
*/
Ob_start ();
Ob_implicit_flush (0 );
Function CheckCanGzip (){
Global $ HTTP_ACCEPT_ENCODING;
If (headers_sent () | connection_timeout () | connection_aborted ()){
Return 0;
}
If (strpos ($ HTTP_ACCEPT_ENCODING, 'X-gzip ')! = False) return "x-gzip ";
If (strpos ($ HTTP_ACCEPT_ENCODING, 'gzip ')! = False) return "gzip ";
Return 0;
}
/* $ Level = compression level 0-9, 0 = none, 9 = max */
Function GzDocOut ($ level = 1, $ debug = 0 ){
$ ENCODING = CheckCanGzip ();
If ($ ENCODING ){
Print "n N ";
$ Contents = ob_get_contents ();
Ob_end_clean ();
If ($ debug ){
$ S ="

This is a piece of code from catoc a long time ago. it was seen in weblogs.com. he used the zlib function to compress the transmitted content. the test shows that for pages larger than 10 KB, the larger the page, the more obvious the effect ......

Not compress length: " . strlen($Contents);
$s .= "Compressed length: " . strlen(gzcompress($Contents, $level));
$Contents .= $s;
}
header("Content-Encoding: $ENCODING");
print "x1fx8bx08x00x00x00x00x00";
$Size = strlen($Contents);
$Crc = crc32($Contents);
$Contents = gzcompress($Contents, $level);
$Contents = substr($Contents, 0, strlen($Contents) - 4);
print $Contents;
print pack('V', $Crc);
print pack('V', $Size);
exit;
} else {
ob_end_flush();
exit;
}
}

?>

The export Output Control function allows you to freely Control the Output of data in the script. It is very useful, especially for: when you want...

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.