首页> PHP笔记> >php使用fsockopen异步处理

php使用fsockopen异步处理

时间:2023-07-06 浏览次数:1330

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


function request_by_fsockopen($url,$post_data=array()){
    $url_array = parse_url($url);
    $hostname = $url_array['host'];
    $port = isset($url_array['port'])? $url_array['port'] : 80;
    $requestPath = $url_array['path'] ."?". $url_array['query'];
    $fp = fsockopen($hostname, $port, $errno, $errstr, 10);
    if (!$fp) {
        echo "$errstr ($errno)";
        return false;
    }
    $method = "GET";
    if(!empty($post_data)){
        $method = "POST";
    }
    $header = "$method $requestPath HTTP/1.1\r\n";
    $header.="Host: $hostname\r\n";
    if(!empty($post_data)){
        $_post = strval(NULL);
        foreach($post_data as $k => $v){
                $_post[]= $k."=".urlencode($v);//必须做url转码以防模拟post提交的数据中有&符而导致post参数键值对紊乱
        }
        $_post = implode('&', $_post);
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";//POST数据
        $header .= "Content-Length: ". strlen($_post) ."\r\n";//POST数据的长度
        $header.="Connection: Close\r\n\r\n";//长连接关闭
        $header .= $_post; //传递POST数据
    }else{
        $header.="Connection: Close\r\n\r\n";//长连接关闭
    }
    fwrite($fp, $header);
    //-----------------调试代码区间-----------------
    /*$html = '';
    while (!feof($fp)) {
        $html.=fgets($fp);
    }
    echo $html;*/
    //-----------------调试代码区间-----------------
    fclose($fp);
}

$data = array(
    'name'=>'张三',
    'email'=>'123@qq.com',
    'mobile'=>'13688888888',
    'content'=>'这是留言内容'
    );
echo microtime(),"\r\n";
request_by_fsockopen('http://jk70.cn/index.php?m=Comment&a=sendEmail',$data); // 访问处理邮件的方法,不管有没返回结果程序都将往下执行
echo microtime();

    相关推荐

    十年网站建设

      建立本站初衷,是为了记录学习过程中掌握的方法,或者项目开发过程中遇到问题的解决方案,防止后面遇到同样的问题时却忘了当时的解决方法,以此有个地方回顾!

      需求合作:479083651@qq.com
      发送邮件请说明您的需求!

    阅读排行