I have seen many versions of PHP asynchronous request methods on the Internet. Here I will summarize several common methods and share them with you.
1. Use CURL to implement one-step Request
CURL extension is the most commonly used method in the development process. It is a powerful HTTP command line tool that can simulate POST/GET and other HTTP requests and then obtain and extract data, displayed on stdout.
Example:
Copy codeThe Code is as follows:
<? Php
$ Cl = curl_init ();
$ Curl_opt = array (CURLOPT_URL, 'HTTP: // www.uncletoo.com/demo.php ',
CURLOPT_RETURNTRANSFER, 1,
CURLOPT_TIMEOUT, 1 ,);
Curl_setopt_array ($ cl, $ curl_opt );
Curl_exec ($ ch );
Curl_close ($ ch );
?>
Because the minimum value of the CUROPT_TIMEOUT attribute is 1, this means that the client must wait for 1 second, which is also a disadvantage of using the CURL method.
2. Use the popen () function to Implement Asynchronous requests
Syntax format: popen (command, mode)
Example:
Copy codeThe Code is as follows:
<? Php
$ File = popen ("/bin/ls", "r ");
// The code to be executed
//...
Pclose ($ file );
?>
The popen () function directly opens a pipeline pointing to a process, which is fast and instantly appropriate. However, this function is a single function, either read or write, and if the number of concurrency is large, a large number of processes will be generated, causing a burden on the server.
In addition, as in the example, the program must be closed with pclose.
3. Use the fscokopen () function to Implement Asynchronous requests
We usually use this function when developing the mail sending function and other socket programming. before using this function, we need to go to PHP. enable the allow_url_fopen option in ini. In addition, we also need to manually splice the header part.
Example:
Copy codeThe Code is as follows:
$ Fp = fsockopen ("www.uncletoo.com/demo.php", 80, $ errno, $ errstr, 30 );
If (! $ Fp ){
Echo "$ errstr ($ errno) <br/> \ n ";
} Else {
$ Out = "GET/index. php/HTTP/1.1 \ r \ n ";
$ Out. = "Host: www.uncletoo.com \ r \ n ";
$ Out. = "Connection: Close \ r \ n ";
Fwrite ($ fp, $ out );
/* Ignore the execution result here
* It can be opened during testing.
While (! Feof ($ fp )){
Echo fgets ($ fp, 128 );
}*/
Fclose ($ fp );
}
PHP itself does not have multithreading, but we can use other methods to achieve the effect of multithreading. The three methods listed above have their own advantages and disadvantages. You can choose the best option based on the needs of the program during use.
UncleToo experience is not very simple. Here is a summary of so much. If there are other better methods to implement PHP multithreading, we can discuss it together!