方法1
<?php
$url = 'http://www.baidu,com';
$sock_data = array('user_id' => 10002);
$result = doRequest($url, $sock_data);//异步调用
function doRequest($url,$param){
$urlinfo= parse_url($url);
$host= $urlinfo['host'];
$path= $urlinfo['path'];
$query= isset($param)? http_build_query($param): '';
$port= 80;
$errno= 0;
$errstr= '';
$timeout= 10;
$fp= fsockopen($host, $port, $errno, $errstr, $timeout);
$out= "POST ".$path." HTTP/1.1\r\n";
$out.= "host:".$host."\r\n";
$out.= "content-length:".strlen($query)."\r\n";
$out.= "content-type:application/x-www-form-urlencoded\r\n";
$out.= "connection:close\r\n\r\n";
$out.= $query;
fputs($fp, $out);
fclose($fp);
}
方法2
/**
* php异步调用
*/
function sock_data($url,$port=80,$t=30,$method='get',$data=null)
{
$info=parse_url($url);
if($this->httpcodeCheck($info["host"])){
$fp = @fsockopen($info["host"],$port, $errno, $errstr,$t);
if (!$fp) {
file_put_contents("yibu.txt",$info["host"]."连接失败".PHP_EOL,FILE_APPEND);
return '连接失败';
}
if ($errno || !$fp) {
file_put_contents("yibu.txt",$info["host"].$errstr.PHP_EOL,FILE_APPEND);
return $errstr;
}
// 判断是否有数据
if(isset($data) && !empty($data)) {
$query = http_build_query($data); // 数组转url 字符串形式
}else {
$query=null;
}
// 如果用户的$url "http://www.xxx.com/"; 缺少 最后的反斜杠
if(!isset($info['path']) || empty($info['path'])) {
$info['path']="/index.html";
}
// 判断 请求方式
if($method=='post'){
$head = "POST ".$info['path']." HTTP/1.0".PHP_EOL;
}else{
$head = "GET ".$info['path']."?".$query." HTTP/1.0".PHP_EOL;
}
$head .= "Host: ".$info['host'].PHP_EOL; // 请求主机地址
$head .= "Referer: http://".$info['host'].$info['path'].PHP_EOL;
if(isset($data) && !empty($data) && ($method=='post')){
$head .= "Content-type: application/x-www-form-urlencoded".PHP_EOL;
$head .= "Content-Length: ".strlen(trim($query)).PHP_EOL;
$head .= PHP_EOL;
$head .= trim($query);
}else{
$head .= PHP_EOL;
}
$write = fputs($fp, $head); //写入文件(可安全用于二进制文件)。 fputs() 函数是 fwrite() 函数的别名
while (!feof($fp))
{
$line = fread($fp,4096);
//echo $line;
}
}else{
file_put_contents("yibu.txt",$info["host"]."---ping:".$this->httpcodeCheck($info["host"]).PHP_EOL,FILE_APPEND);
}
}
//检查域名是否能ping通
function httpcodeCheck($url){
$ch = curl_init();
$timeout =50;
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,$timeout);
curl_setopt($ch,CURLOPT_URL,$url);
curl_exec($ch);
return $httpcode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
}
//调用方法
$url='http://www.baidu.com';
$sock_data = array('id'=>1);
$this->sock_data($url,80,30,'get',$sock_data);//异步调用