通过fsockopen实现异步调用php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
function triggerRequest($url,$post_data = [],$cookie = []) { $method = 'GET'; $url_array = parse_url($url); $url_array['port'] = $url_array['scheme'] == 'https'?443:80; $url_array['scheme'] = $url_array['scheme'] == 'https'?'ssl://':'tcp://'; $url_array['query'] = isset($url_array['query'])?'?'.$url_array['query']:''; $url_array['path'] = isset($url_array['path'])?$url_array['path']:'/'; $fp = fsockopen($url_array['scheme'].$url_array['host'].':'.$url_array['port'].$url_array['path'].$url_array['query'],$url_array['port'],$errno,$errstr,30); if(!$fp) return FALSE; if(!empty($post_data)) $method = 'POST'; $header = $method." ".$url_array['path']." HTTP/1.1\r\n"; $header .= "Host: ".$url_array['host']."\r\n"; //HTTP 1.1 Host域不能省略 $header .= "Connection: Close\r\n\r\n"; if(!empty($cookie)){ $_cookie = strval(NULL); foreach($cookie as $k => $v){ $_cookie .= $k."=".$v."; "; } $cookie_str = "Cookie: " . base64_encode($_cookie) ." \r\n";//传递Cookie $header .= $cookie_str; } if(!empty($post_data)){ $_post = strval(NULL); foreach($post_data as $k => $v){ $_post .= $k."=".$v."&"; } $post_str = "Content-Type: application/x-www-form-urlencoded\r\n";//POST数据 $post_str .= "Content-Length: ". strlen($_post) ." \r\n";//POST数据的长度 $post_str .= $_post."\r\n\r\n "; //传递POST数据 $header .= $post_str; } fwrite($fp, $header); //我们不关心服务器返回 /*while(!feof($fp)) { echo fgets($fp,128); }*/ fclose($fp); return true; } |