/**
* 发送一个异步http协议的Get请求,不用关心结果
* @param $url
* @param $errno
* @param $errstr
* @param $time_out
*/
static public function getAsn($url,$errno='',$errstr='',$time_out = 5) {
//移除url中的空格,如果可以格式化url,或许会更好
$url = str_replace(' ', '', $url);
$arr = parse_url($url);
$arr['port'] || $arr['port'] = 80;
$fp = fsockopen($arr['host'],$arr['port'],$errno,$errstr,$time_out);
if(!$fp) {
return $errno." ".$errstr;
}
$arr['query'] && $arr['query'] = '?'.$arr['query'];
$out = "GET ".$arr['path'].$arr['query']." HTTP/1.1\r\n";
$out .= "Host: ".$arr['host']."\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp,$out);
fclose($fp);
}
/**
* 异步post
* @param $url
* @param $post_arr
* @param $errno
* @param $errstr
* @param $time_out
*/
static function postAsn($url,$post_arr,$errno = '',$errstr='',$time_out = 5) {
$arr = parse_url($url);
$arr['port'] || $arr['port'] = 80;
$fp = fsockopen($arr['host'],$arr['port'],$errno,$errstr,$time_out);
if(!$fp) {
return $errno." ".$errstr;
}
$post_data = "";
if($post_arr){
//在这里还可以使用 http_build_query() 函数,将post的内容编码
foreach ($post_arr as $key => $val){
$post_data .= urlencode($key) ."=". urlencode($val)."&";
}
$post_data = substr($post_data, 0,-1);
}
$data_len = strlen($post_data);
$arr['query'] && $arr['query'] = '?'.$arr['query'];
$out = "POST ".$arr['path'].$arr['query']." HTTP/1.1\r\n";
$out .= "Host: ".$arr['host']."\r\n";
$out .= "Content-type:application/x-www-form-urlencoded\r\n";
$out .= "Connection: Close\r\n";
$out .= "Content-Length:$data_len\r\n\r\n";
$out .= $post_data."\r\n";
fwrite($fp,$out);
fclose($fp);
}
网站标题:php中用来可以做异步调用的代码
文章网址:
http://cdxtjz.cn/article/pdggsh.html