php使用fsockopen异步处理

常见场景:提交留言板,并发送邮件通知管理员。如果这时要等待发送邮件的操作处理完,那将花费很长时间,用户体验不好,所以发邮件的处理应该改成异步。

 1 function request_by_fsockopen($url,$post_data=array()){
 2     $url_array = parse_url($url);
 3     $hostname = $url_array['host'];
 4     $port = isset($url_array['port'])? $url_array['port'] : 80; 
 5     $requestPath = $url_array['path'] ."?". $url_array['query'];
 6     $fp = fsockopen($hostname, $port, $errno, $errstr, 10);
 7     if (!$fp) {
 8         echo "$errstr ($errno)";
 9         return false;
10     }
11     $method = "GET";
12     if(!empty($post_data)){
13         $method = "POST";
14     }
15     $header = "$method $requestPath HTTP/1.1\r\n";
16     $header.="Host: $hostname\r\n";
17     if(!empty($post_data)){
18         $_post = strval(NULL);
19         foreach($post_data as $k => $v){
20                 $_post[]= $k."=".urlencode($v);//必须做url转码以防模拟post提交的数据中有&符而导致post参数键值对紊乱
21         }
22         $_post = implode('&', $_post);
23         $header .= "Content-Type: application/x-www-form-urlencoded\r\n";//POST数据
24         $header .= "Content-Length: ". strlen($_post) ."\r\n";//POST数据的长度
25         $header.="Connection: Close\r\n\r\n";//长连接关闭
26         $header .= $_post; //传递POST数据
27     }else{
28         $header.="Connection: Close\r\n\r\n";//长连接关闭
29     }
30     fwrite($fp, $header);
31     //-----------------调试代码区间-----------------
32     /*$html = '';
33     while (!feof($fp)) {
34         $html.=fgets($fp);
35     }
36     echo $html;*/
37     //-----------------调试代码区间-----------------
38     fclose($fp);
39 }
40  
41 $data = array(
42     'name'=>'张三',
43     'email'=>'123@qq.com',
44     'mobile'=>'13688888888',
45     'content'=>'这是留言内容'
46     );
47 echo microtime(),"\r\n";
48 request_by_fsockopen('http://jk70.cn/index.php?m=Comment&a=sendEmail',$data); // 访问处理邮件的方法,不管有没返回结果程序都将往下执行
49 echo microtime();

 

posted @ 2020-08-30 23:42  好记随笔  阅读(193)  评论(0)    收藏  举报