Three ways to implement PHP multithreaded asynchronous requests

  • 2020-12-19 20:56:39
  • OfStack

I have seen many versions of PHP asynchronous request method on the Internet, here are a few common methods to share with you

1. Use CURL to realize the 1-step request

The CURL extension is one of the most commonly used methods in the development process. It is a powerful HTTP command line tool that simulates HTTP requests such as POST/GET, and then obtains and extracts the data to display on the "standard Output" (stdout).

Example:
 
<?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); 
?> 

Since the CUROPT_TIMEOUT attribute has a minimum value of 1, this means that you must wait 1 second on the client side, which is also a disadvantage of using the CURL method

2. Use popen() function to realize asynchronous request

Grammar format: popen(command,mode)

Example:
 
<?php 
$file = popen("/bin/ls","r"); 
// Here is the code to execute  
//... 
pclose($file); 
?> 

popen() function directly opens a pipeline pointing to the process, with fast speed and instant response. However, this function is a singleton, either read or write, and if the number of concurrenciations is large, it can create a large number of processes, putting a strain on the server.

Also, as in the example 1, when the program ends, 1 must be closed with pclose().

3. Use fscokopen() to implement asynchronous requests

We always use this function when developing socket programming such as email sending function. Before using this function, we need to turn on the allow_url_fopen option in ES43en.ini. In addition, we need to manually splicheader part when it becomes ini.

Example:
 
$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\r\n"; 

fwrite($fp, $out); 
/* The execution results are ignored here  
* It can be turned on during testing  
while (!feof($fp)) { 
echo fgets($fp, 128); 
}*/ 
fclose($fp); 
} 

PHP itself does not have multithreading, but there are other ways to achieve the effect of multithreading. The three methods listed above all have their own advantages and disadvantages, and you can choose according to the needs of the program when you use it.

UncleToo experience is still shallow, here is a simple summary of so much, if there are other better ways to implement PHP multithreading can be discussed 1!

Related articles: