In-depth explanation of PHP asynchronous execution _ php instance

Source: Internet
Author: User
This article provides a detailed analysis of PHP asynchronous execution. If you need a friend, refer to the Web server to execute a PHP script. Sometimes it takes a long time to return the execution result, the subsequent scripts will take a long time to continue execution. To execute the next operation without waiting for the execution result, you can use the fscokopen function.
PHP supports socket programming. The fscokopen function returns a remote host connection handle, which can be fwrite, fgets, fread, and other operations like the handle returned by fopen. Use fsockopen to connect to the local server, trigger script execution, and then return immediately. You can implement asynchronous PHP Execution without waiting for the script execution to complete.
The sample code is as follows:

The Code is as follows:


Function triggerRequest ($ url, $ post_data = array (), $ cookie = array ()){
$ Method = "GET"; // pass some parameters to the script to be triggered through POST or GET
$ Url_array = parse_url ($ url); // obtain URL Information
$ Port = isset ($ url_array ['Port'])? $ Url_array ['Port']: 80;
$ Fp = fsockopen ($ url_array ['host'], $ port, $ errno, $ errstr, 30 );
If (! $ Fp ){
Return FALSE;
}
$ GetPath = $ url_array ['path']. "? ". $ Url_array ['query'];
If (! Empty ($ post_data )){
$ Method = "POST ";
}
$ Header = $ method. "". $ getPath;
$ Header. = "HTTP/1.1 \ r \ n ";
$ Header. = "Host:". $ url_array ['host']. "\ r \ n"; // The HTTP 1.1 host domain cannot be omitted.
/* The following header information fields can be omitted
$ Header. = "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: 1.8.1.13) Gecko/20080311 Firefox/2.0.0.13 \ r \ n ";
$ Header. = "Accept: text/xml, application/xml, application/xhtml + xml, text/html; q = 0.9, text/plain; q = 0.8, image/png, q = 0.5 \ r \ n ";
$ Header. = "Accept-Language: en-us, en; q = 0.5 ";
$ Header. = "Accept-Encoding: gzip, deflate \ r \ n ";
*/
$ Header. = "Connection: Close \ r \ n ";
If (! Empty ($ cookie )){
$ _ Cookie = strval (NULL );
Foreach ($ cookie as $ k => $ v ){
$ _ Cookie. = $ k. "=". $ v .";";
}
$ Cookie_str = "Cookie:". base64_encode ($ _ cookie). "\ r \ n"; // pass Cookie
$ Header. = $ cookie_str;
}
If (! Empty ($ post_data )){
$ _ Post = strval (NULL );
Foreach ($ post_data as $ k => $ v ){
$ _ Post. = $ k. "=". $ v ."&";
}
$ Post_str = "Content-Type: application/x-www-form-urlencoded \ r \ n ";
$ Post_str. = "Content-Length:". strlen ($ _ post). "\ r \ n"; // The Length of POST Data
$ Post_str. = $ _ post. "\ r \ n"; // pass POST Data
$ Header. = $ post_str;
}
Fwrite ($ fp, $ header );
// Echo fread ($ fp, 1024); // The Server Returns
Fclose ($ fp );
Return true;
}


In this way, you can use the fsockopen () function to trigger the execution of a PHP script, and then the function will return. Next, perform the next step.
Now there is a problem: when the client is disconnected, that is, the connection is closed immediately after triggerRequest sends a request, it may cause the server to exit with the script being executed correctly.
In PHP, the system maintains the connection status. There are three possible states:
* 0-NORMAL (NORMAL)
* 1-ABORTED (exit unexpectedly)
* 2-TIMEOUT (TIMEOUT)
When the PHP script runs normally, the connection is valid. When the client breaks the connection, the ABORTED status mark will be opened. The interruption of remote client connection is usually caused by the user clicking the STOP button. When the connection time exceeds the PHP time limit (see the set_time_limit () function), the TIMEOUT status mark will be opened.

You can determine whether the script needs to exit when the client terminates the connection. Sometimes it is much more convenient to run the script completely, even if the Script output is not accepted by a remote browser. By default, the script will exit when the remote client connection is interrupted. This process can be controlled by php. ini's ignore_user_abort or by the "php_value ignore_user_abort" and ignore_user_abort () functions in Apache. conf settings. If PHP is not told to ignore user interruptions, the script will be interrupted unless the trigger function is disabled through register_shutdown_function. When a remote user clicks the STOP button and the script tries to output data again, PHP will detect that the connection has been interrupted and call to disable the trigger function.

The script may also be interrupted by the built-in script timer. The default timeout limit is 30 seconds. This value can be changed by setting the "php_value max_execution_time" parameter in the max_execution_time or Apache. conf setting of php. ini or the set_time_limit () function. When the counter times out, the script will exit when the above connection is interrupted, and the previously registered closed trigger function will also be executed at this time. In this function, you can call the connection_status () function to check whether timeout has caused the function to be called. If timeout causes function call to be disabled, the function returns 2.

Note that the ABORTED and TIMEOUT statuses are valid at the same time. It is possible to tell PHP to ignore the user's exit operation. PHP will still note that the user has interrupted the connection but the script is still running. If the running time limit is reached, the script will be exited, And the set function to close and trigger will also be executed. The connection_status () function returns 3.
Therefore, specify the following in the script to be triggered:

The Code is as follows:


Ignore_user_abort (TRUE); // if the client is disconnected, it will not cause the script abort
Set_time_limit (0); // cancels the upper limit of script execution latency
Or use:
Register_shutdown_function (callback fuction [, parameters]); // registers the function executed when the script exits.

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.