PHP basic tutorial PHP page buffer processing mechanism


PHP has a lot of mechanisms and functions. It is actually a magician. If it is repeated well, in fact, even simple applications will have magical effects. Brothers PHP training

Here is an ob_start () function.

  The ob_start() function is used to open the buffer. For example, if there is output before the header() function, including carriage return\space\linefeed\, there will be an error of "Header had all ready send by", then you can use ob_start() first Open buffer The data block and echo() output of PHP code will enter the buffer and will not be output immediately. Of course, opening the buffer has many functions, as long as you use your imagination. The following four points can be summarized:

  1. Used for header() Before

  ob_start(); //Open the buffer

  echo \"Hellon\"; //Output

  header("location:index.php");//Redirect the browser to index.php

  ob_end_flush();//Output all Content to the browser

  ?>

  2. The phpinfo() function can obtain the information of the client and the server, but the buffer method to save the client information is the best choice.

  ob_start(); //Open the buffer

  phpinfo() ; //Use the phpinfo function

  $info=ob_get_contents(); //Get the contents of the buffer and assign it to $info

  $file=fopen(\'info.txt\',\'w\');//Open the file info .txt

  fwrite($file,$info); //Write information to info.txt

  fclose($file); //Close the file info.txt

  ?>

  3. Static page technology

  ob_start();//Open the buffer

  ?>

  All the output of the php page

  $content =ob_get_contents();//Get the output of the php page Full content

  $fp =fopen("output00001.html", "w"); //Create a file, open it, and prepare to write

  fwrite($fp, $content); //Write all the content of the php page to output00001 .html, then...

  fclose($fp);

  ?>

  4. Output code

  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 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 header after the data has been output. The output control function has no effect on the header information sent using header() or setcookie(), only on data blocks like echo() and PHP code.

  Let's give a simple example to give you a general impression of OutputControl:

  Example 1.

  CODE<?php

  ob_start(); //Open the buffer

  echo \"Hellon\"; //Output

  header("location:index .php");//Redirect the browser to index.php

  ob_end_flush();//Output all content to the browser

  ?>

  Anyone who knows the header() function knows that this function will send a file header to the browser, but an error will be raised if there is any output (including empty output, such as spaces, carriage returns and line feeds) before using this function. If we remove the ob_start() in the first line and execute this program again, we will find that we get an error message: "Header hadall ready send by"! But with ob_start, there will be no error message, because when the buffer is opened In the area, the characters after echo will not be output to the browser, but will be kept on the server until you use flush or ob_end_flush, so there will be no errors in the output of the file header!

  1. Introduction to related functions:

  1. Flush : Flush the contents of the buffer, output.

  Function format: flush()

  Description: This function is often used and is very efficient.

  2. ob_start: Open the output buffer

  Function format: void ob_start(void)

  Description: When the buffer is activated, all non-file header information from the PHP program will not be sent, but will be stored in the internal buffer. To output the contents of the buffer, use ob_end_flush() or flush() to output the contents of the buffer.

  3. ob_get_contents: Returns the content of the internal buffer.

  Usage: stringob_get_contents(void)

  Description: This function will return the content in the current buffer, or FALSE if the output buffer is not activated.

  4. ob_get_length: Returns the length of the internal buffer.

  Usage: intob_get_length(void)

  Description: This function will return the length in the current buffer; same as ob_get_contents, if the output buffer is not activated. Returns FALSE.

  5. ob_end_flush: Send the content of the internal buffer to the browser and close the output buffer.

  Usage: voidob_end_flush(void)

  Description: This function sends the content of the output buffer (if any).

  6. ob_end_clean: delete the content of the internal buffer and close the internal buffer

  Usage : void ob_end_clean(void)

  Description: This function will not output the content of the internal buffer but delete it!

  7. ob_implicit_flush: Open or close absolute

  flushing Method: void ob_implicit_flush([int flag])

  Description: Anyone who has used Perl knows the meaning of $|=x, this string can open/close the buffer, and the ob_implicit_flush function also Like that, the default is to close the buffer. After the absolute output is turned on, each script output is directly sent to the browser, and there is no need to call flush   (   )

  . It is a very efficient function. It has a very useful function to refresh the browser's cache. Let's take an example with a very obvious running effect to illustrate flush.   Example 2.   CODE<?php   for($i = 1 ; $i <= 300; $i++ ) print(" ");   // This sentence is very critical, the structure of the cache makes its content only output from the browser if it reaches a certain size   // In other words, if the content of the cache If it does not reach a certain size, it will not be output before the program finishes executing. After   // testing, I found that the bottom limit of this size is 256 characters long. This means that the content that the cache receives in the future will   // be sent out continuously.   For($j = 1; $j <= 20;$j++) {   echo $j."   ";   flush(); //This part will cause the newly added content of the cache to be squeezed out and displayed on the browser



























  sleep(1); //Let the program "sleep" for a second, you can see the effect more clearly

  }

  ?>

  You can check the specific effect here http://www.php2000.com/~uchinaboy/out .php

  PHP2000's latest PHP chat room uses this technology. Unfortunately, the source code is not disclosed.

  Note: If you add ob_implicit_flush() to the head of the program to enable absolute refresh, you can no longer use flush() in the program. The advantage of this is: improve efficiency!

  2. Regarding the ob series functions:

  I would like to quote an example from my good friend y10k:

  Example 3. For

  example, you can get the setting information of the server and the client, but this information will be changed because of the client's Different and different, what if you want to save the output of the phpinfo() function? Before there is no buffer control, it can be said that there is no way, but with the buffer control, we can easily solve:

  CODE<?php

  ob_start(); //Open the buffer

  phpinfo(); //Use the phpinfo function

  $info=ob_get_contents(); //Get the contents of the buffer and assign it to $info

  $file=fopen(\'info.txt\', \'w\');//Open the file info.txt

  fwrite($file,$info); //Write information to info.txt

  fclose($file); //Close the file info.txt

  ?>

  Using the above method, you can save the phpinfo information of different users, which I am afraid there is no way to do it before! In fact, the above is a method of converting some "processes" into "functions"!

  Some people may ask: "Is it Is it like this? Are there any other uses?" Of course, there is, for example, the PHP syntax highlighting in the author's forum is related to this (PHP's default syntax highlighting function will output directly, and the result cannot be saved. Calls are displayed, I am afraid it will be a waste of CPU, the author's forum has reserved the results of the syntax highlighting function by controlling the buffer), if you are interested, you can take a look at http://www.zphp.com/ bbs/ !

  Maybe now everyone has a certain understanding of the function of ob_start(). The above example seems simple, but in fact, you have mastered the key points of using ob_start().

  <1>. Use ob_start to open the browser's cache, which ensures that the contents of the cache will not be output before you call flush(), ob_end_flush() (or the program is executed).

  < 2>. Now you should know the advantages you have: you can use header, setcookie and session after any output content, which is a big feature of ob_start; you can also use the parameters of ob_start, after the cache is written , and then automatically run the command, such as ob_start(\"ob_gzhandler\ "); and our most common practice is to use ob_get_contents() to get the content in the cache, and then process it...

  <3>. After processing, we can Use various methods to output, flush(), ob_end_flush(), and automatic output after the program is executed. Of course, if you use ob_get_contents(), then you have to control the output yourself.

  Come, let's see what we can do with the ob series

  of functions... 1. Static template technology

  Introduction : The so-called static template technology is to make the user get the html page generated by PHP in a certain way on the client side. If this html page will not be updated again, 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, such as sina, 163, and sohu. The benefits of technologies like this are enormous.

  As far as I know, there are two ways to achieve static output:

  <1>. A class called template.inc.php of phplib modified by y10k is implemented.

  <2>. Use the ob series of functions to achieve.

  For the first method, because it is not the problem to be studied in this article, it will not be repeated.

  Let's now take a look at the specific implementation of the second method:

  Example 4.

  CODE<?php

  ob_start();//Open the buffer

  ?>

  All output of the php page

  <?

  $content =ob_get_contents();//Get php The entire content of the page output

  $fp =fopen("output00001.html", "w"); //Create a file and open it, ready to write

  fwrite($fp, $content); //All the content of the php page Write output00001.html, then...

  fclose($fp);

  ?>

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

  2. Capture output The

  above Example 4. is the simplest case, you can also operate on $content before writing...

  You can try to capture Some keywords, and then go to it for reprocessing, such as PHP syntax highlighting as described in Example3. Personally, this function is the biggest essence of this function. It can solve all kinds of problems, but it requires you to have enough imagination...

  Example 5.

  CODE<?

  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 purpose of the above example is not It's very big, but it is typical that $code itself is an output page containing variables, and this example uses eval to replace the variables in $code, and then the output results are captured and processed again...

  Example 6. Speed ​​up transmission

  CODE<?

  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;

  }

  functionGzDocOut($level=1,$debug=0){

  $ENCODING = CheckCanGzip();

  if ($ENCODING){

  print \”n<!– Usecompress $ENCODING –>n\”;

  $Contents =ob_get_contents();

  ob_end_clean();

  if ($debug){

  $s = \”<p>Notcompress length: \”.strlen($Contents);

  $s .= \”

  Compressed length:\”.strlen(gzcompress($Contents,$level));

  $Contents .= $s;

  }

  header(\”Content-Encoding:$ENCODING\”);

  print\”x1fx8bx08×00x00×00x00×00 \";

  $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;

  }

  }

  ?>

  this is catoc A piece of code from a long time ago was seen on weblogs.com. He used the function of zlib to compress the transmitted content. The test showed that for pages over 10k, it would have an effect, and the larger the page, The more obvious the effect...


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326480882&siteId=291194637