使用fsocketopen封装发送post请求的方法(不等待返回结果,只负责发送post请求,可用于异步处理)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37281289/article/details/86554400
// 传入的$param的格式为数组格式如:
// $url 如 http://www.example.com/admin/index/method
// $param = array( 'name' => 'hello', 'lastname' => 'world')
// $timeout 超时时间单位秒, 不传入默认5秒

function requestBySocket($url, $param, $timeout = 5)
{
    $urlinfo = parse_url($url);

    $host = $urlinfo['host'];
    $path = $urlinfo['path'];
    $query = isset($param)? http_build_query($param) : '';
    $port = 80;
    $errno = 0;
    $errstr = '';

    $fp = fsockopen($host, $port, $errno, $errstr, $timeout);

    if (!$fp) {
        return array('error_code' => $errno, 'error_msg' => $errstr);
    } else {
        stream_set_blocking($fp, 0);//开启了手册上说的非阻塞模式
        stream_set_timeout($fp, 2);//设置超时, 2s
        $header = "POST ".$path." HTTP/1.1\r\n";
        $header .= "host:".$host."\r\n";
        $header .= "content-length:".strlen($query)."\r\n";
        $header .= "content-type:application/x-www-form-urlencoded\r\n";
        $header .= "connection:close\r\n\r\n";
        $header .= $query . "\r\n\r\n";     //记住后面一定要加\r\n\r\n 不然数据无法发出

        fputs($fp, $header);
        usleep(1000); // 这一句也是关键,如果没有这延时,可能在nginx服务器上就无法执行成功
        fclose($fp);
        return array('error_code' => 0);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_37281289/article/details/86554400