In PHP, the two methods are executed at the end of the request. The method names are register_shutdown_function and Fastcgi_finish_request, respectively. Although the timing is similar, the functionality and application scenarios are different. The difference between the two methods is not the focus of this article. This article focuses on the application scenarios of the two methods.
Register_shutdown_function
Features:
Registers a method that calls this method of registration when a request is completed. Note that the registration method executes even if an error occurs during execution that causes the request to be forced out.
Application Scenario One:
Can take advantage of his features to capture some of the error details. The sample code is as follows:
function Catch_error () { $error = error_get_last (); if ($error) { var_dump($error); }} register_shutdown_function ("Catch_error"); Ini_set (' Memory_limit ', ' 1M '); $content str_repeat ("Aaaaaaaaaaaaaaaaaaaaaaa", 100000); Echo "AA";
The output information might look like this:
Array (4) {["type"]=> int (1) ["Message"]=> string "allowed memory size of 1048576 bytes exhausted (tried to Allo Cate 2300001 bytes) "[" File "]=> string"/test.php "[" Line "]=> int (13)}
As you can see, the above code correctly captures an out-of-memory error.
Application Scenario Two
Check whether the request shuts down properly. The sample code is as follows:
functionMonitor () {Global $is _end; if($is _end==true){ Echo"Success"; }Else{ Echo"Fail"; }}register_shutdown_function("Monitor");$is _end=false; die();$is _end=true;
The page output results are: fail
Visible, even if the die function is called. The registered monitor function is also executed correctly.
Fastcgi_finish_request
Features:
Flush data to the client. Once this method is called, any output will not be output to the client.
Application Scenarios:
If a part of the processing of a request is not required to be sent to the client, the output to the client's content can be generated before calling this method. When the method is called, the content is output to the client. Instead of having to output the content to the client, you can put it behind this method. This can improve response times. The sample code is as follows:
Echo "A"; Fastcgi_finish_request (); Echo "B"; file_put_contents ("/tmp/test", "bo56.com"); die (); file_put_contents ("/tmp/b56", "knowledgeable and carefree");
The results of the page output are: a
As can be seen, the echo "B" after the Fastcgi_finish_request method is not output to the client. However, you will find that the files are created normally under the/tmp/test directory. However, the/tmp/bo56 file was not created.
Register_shutdown_function and Fastcgi_finish_request in PHP