Use fsockopen () to call PHP asynchronously

Source: Internet
Author: User
Use fsockopen () to call PHP asynchronously

Author: laruence (http://www.laruence.com)
Address: http://www.laruence.com/2008/04/16/98.html
The Web server may execute a script in several milliseconds or minutes. If the program runs slowly and the user may not be patient, the browser will be closed.
Sometimes, we don't care about the execution results of these time-consuming scripts, but we have to wait for them to execute and return before continuing the next step.
Is there any way to simply trigger and call these time-consuming scripts and then proceed to the next step so that these time-consuming scripts can be executed slowly on the server?

Next, I will use fscokopen to implement this function.

PHP supports socket programming, that is, fsockopen. I used it for smtp sending when I used CMS.
Fscokopen returns a remote host connection handle. You can perform fwrite, read fgets, fread, and other operations on her like using the handle returned by fopen.

The main result of our asynchronous PHP is to trigger a PHP script and return immediately, leaving it to be executed slowly on the server side. I have also written an article to discuss this issue.

Then, we can use fsockopen to connect to the local server, trigger script execution, and then return immediately without waiting for the script to be executed.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 // + ---------------------------------------------------------------------- // FunctiontriggerRequest ($ url, $ post_data = array (), $ cookie = array ())... {$ Method = "GET"; // you can pass some parameters through POST or GET to the script to be triggered $ url_array = parse_url ($ url); // obtain URL information, so that we can combine http header $ port = isset ($ url_array ['port'])? $ Url_array ['port']: 80; $ fp = fsockopen ($ url_array ['host'], $ port, $ errno, $ errstr, 30); if (! $ Fp )... {ReturnFALSE;} $ 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/**/$ 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 ($ cookieas $ 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_dataas $ k => $ v )... {$ _ Post. = $ k. "= ". $ v. "&" ;}$ post_str = "Content-Type: application/x-www-form-urlencoded \ r \ n"; // POST data $ post_str. = "Content-Length:". strlen ($ _ post ). "\ r \ n"; // The length of the POST Data $ post_str. = $ _ post. "\ r \ n"; // transmits the POST data $ header. = $ post_str;} fwrite ($ fp, $ header); // echo fread ($ fp, 1024); // we don't care if the server returns fclose ($ fp ); returntrue;}?>

Now, you can use this function to trigger the execution of a PHP script, and then the function will return. We can proceed to the next step.

Another problem is when the client is disconnected. That is, after triggerRequest sends a request, the connection is immediately closed, which may cause the server to exit after executing the script.

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:

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
Alternatively, you can 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.