Detail common ways of asynchronous execution based on PHP

  • 2020-06-03 06:02:28
  • OfStack

1. The client page USES AJAX technology to request the server
Advantage: The simplest and fastest method is to embed the AJAX call in the HTML code returned to the client, or embed an img tag that points to the time-consuming script to execute.
Disadvantages: 1 Generally, Ajax should be triggered after onLoad, that is, after the user clicks the page, it is closed, so our background script will not be triggered.
With the img tag, this approach is not strictly asynchronous. The user's browser will have to wait a long time for the php script to complete, meaning that the user's status bar will still be displayed in load.
Of course, there are other similar principles that can be used, such as the script tag, and so on.
2. popen () function
This function opens a pipe to the process that is executed by deriating the given command command. Open a pipe to the process that is executed by deriating the given command command.
So you can call it, but ignore its output. The code is as follows:

pclose(popen("/home/xinchen/backend.php &", 'r'));

Pros: Avoids the pitfalls of the first approach, and is fast.
Cons: This method does not request another WebService via the HTTP protocol, only local script files are executed. And can only be opened in one direction, can not wear a large number of parameters to the called script. And if you have a lot of traffic, you have a lot of processes. If external resources are used, consider the competition yourself.
3. CURL extension
CURL is a powerful HTTP command line tool that simulates HTTP requests such as POST/GET, and then gets and extracts the data to be displayed on "standard Output" (stdout). The code is as follows:

$ch = curl_init();
$curl_opt = array(CURLOPT_URL, 'http://www.example.com/backend.php',
                            CURLOPT_RETURNTRANSFER, 1,
                            CURLOPT_TIMEOUT, 1,);
curl_setopt_array($ch, $curl_opt);
curl_exec($ch);
curl_close($ch);

Cons: As described in your question, using CURL requires setting CUROPT_TIMEOUT to 1 (min. 1, depressing). That is, the client must wait at least 1 second.
4. fscokopen () function
fsockopen supports socket programming, you can use fsockopen to send mail and other socket programs, etc., using fcockopen need to manually splice out the header part
Use examples are as follows:

$fp = fsockopen("www.34ways.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET /index.php  / HTTP/1.1\r\n";
    $out .= "Host: www.34ways.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    /* Ignore execution results 
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }*/
    fclose($fp);
}

So in summary, the fscokopen() function should suffice. You could try 1.

Related articles: