// 传入的$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); } }
使用fsocketopen封装发送post请求的方法(不等待返回结果,只负责发送post请求,可用于异步处理)
最新推荐文章于 2021-03-13 05:51:12 发布