Home  >  Article  >  Backend Development  >  PHP asynchronous call implementation method

PHP asynchronous call implementation method

巴扎黑
巴扎黑Original
2016-11-23 13:17:191080browse

There is only a connectionless-oriented HTTP protocol for communication between the browser and the server. The characteristic of connectionless-oriented programs is that the client requests the server, and the server outputs the corresponding program according to the request, and cannot maintain a persistent connection.

There is a problem. The corresponding server of a client may execute for 1 second or for 1 minute. In this way, the browser will always be in a waiting state. If the program executes slowly, the user may not have the patience to close the browser. .

Sometimes we don’t need to care about the results of program execution. There is no need to waste time and wait patiently like this. Then we have to find a way to make the program execute silently in the background without waiting.

For example, there is a scenario where a recommendation email is sent to 1,000 users. The user enters or imports the email account and submits it to the server for sending.

<?php  
$count=count($emailarr);for($i=0;$i<$count;$i++)  
{  
  sendmail(.....);//发送邮件  }  ?>

This code has a very poor user experience and cannot be used in practice. First of all, sending so many emails will cause the server to run timeout. In fact, the long user waiting time will make users doubt and lose confidence in the system product. However, the user does not need to wait until all 1,000 emails have been sent before submitting the message successfully. We can directly prompt the user to send the message successfully after submitting it to the background, and then let the background program silently send it one by one.

At this time we need "asynchronous execution" technology to execute the code. The characteristic of asynchronous execution is silent execution in the background. The user does not need to wait for the execution result of the code. The benefits of using asynchronous execution:

1. Get rid of the application's responsibility for a single task Dependencies

2. Improve the execution efficiency of the program

3. Improve the scalability of the program

4. Improve the user experience in certain scenarios

5. Because PHP does not support multi-threading, use asynchronous call requests The multiple HTTP method achieves the effect of parallel execution of the program, but please note that if too many HTTP requests are made, the system overhead will be greatly increased. AJAX technology request server

1. The simplest way is to embed the AJAX call in the HTML code returned to the client, or embed an img tag with src pointing to the time-consuming script to be executed.

This method is the simplest and fastest. The server does not need to make any calls.

But the disadvantage is that generally Ajax should be triggered after onLoad, that is to say, if the user clicks on the page and then closes it, our background script will not be triggered.

If you use the img tag, this method cannot be called asynchronous execution in the strict sense. The user's browser will wait for a long time for the execution of the php script to be completed, that is, the status bar of the user's browser always shows that it is still loading.

Of course, you can also use other methods with similar principles, such as script tags, etc.




2.popen() function

resource popen (string command, string mode);

//Open a pipe pointing to the process , the process is spawned by the execution of the given command command. Opens a pipe to the process spawned by execution of the command that spawned the given command.

So you can call it but ignore its output.

?


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

This method avoids the shortcomings of the first method and is also fast . But the problem is that this method cannot request another WebService through the HTTP protocol and can only execute local script files. And it can only be opened in one direction, and cannot pass a large number of parameters to the called script.

And if the number of visits is high, a large number of processes will be generated. If you use external resources, you have to consider the competition yourself.

3.CURL extension

CURL is a powerful HTTP command line tool that can simulate POST/GET and other HTTP requests, then get and extract data, and display it on "standard output" (stdout) c548ae991a2514494d285d08966b8e04


$ch = curl_init();

$curl_opt = array(CURLOPT_URL, 'http://www.example.com/backend.php',

                                                             ,

                                                                                                                                                                                                              CURLOPT_TIMEOUT, 1 ,);

curl_setopt_array($ch, $curl_opt);


curl_exec($ch);

curl_close($ch);




To use CURL, you need to set CUROPT_TIMEOUT to 1 (the minimum is 1, depressed). That is, the client must wait at least 1 second. 9b21ee6b58e97765e2a3d44fcda3f6db

4.fscokopen() function

fsockopen is a very powerful function that supports socket programming. You can use fsockopen to implement socket programs such as email sending, etc. You need to manually use fcockopen Splice out the header part


Official document: http://cn.php.net/fsockopen/

?
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET /backend.php  / HTTP/1.1\r\n";
    $out .= "Host: www.example.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
   
    fwrite($fp, $out);
    /*忽略执行结果
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }*/
    fclose($fp);
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP referenceNext article:PHP reference