php使用socket post数据到其它web服务器的方法
本文实例讲述了php使用socketpost数据到其它web服务器的方法。分享给大家供大家参考。具体实现方法如下:
functionpost_request($url,$data,$referer=''){
//ConvertthedataarrayintoURLParameterslikea=b&foo=baretc.
$data=http_build_query($data);
//parsethegivenURL
$url=parse_url($url);
if($url['scheme']!='http'){
die('Error:OnlyHTTPrequestaresupported!');
}
//extracthostandpath:
$host=$url['host'];
$path=$url['path'];
//openasocketconnectiononport80-timeout:30sec
$fp=fsockopen($host,80,$errno,$errstr,30);
if($fp){
//sendtherequestheaders:
fputs($fp,"POST$pathHTTP/1.1\r\n");
fputs($fp,"Host:$host\r\n");
if($referer!='')
fputs($fp,"Referer:$referer\r\n");
fputs($fp,"Content-type:application/x-www-form-urlencoded\r\n");
fputs($fp,"Content-length:".strlen($data)."\r\n");
fputs($fp,"Connection:close\r\n\r\n");
fputs($fp,$data);
$result='';
while(!feof($fp)){
//receivetheresultsoftherequest
$result.=fgets($fp,128);
}
}
else{
returnarray(
'status'=>'err',
'error'=>"$errstr($errno)"
);
}
//closethesocketconnection:
fclose($fp);
//splittheresultheaderfromthecontent
$result=explode("\r\n\r\n",$result,2);
$header=isset($result[0])?$result[0]:'';
$content=isset($result[1])?$result[1]:'';
//returnasstructuredarray:
returnarray(
'status'=>'ok',
'header'=>$header,
'content'=>$content
);
}
//使用方法
//Submitthosevariablestotheserver
$post_data=array(
'test'=>'foobar',
'okay'=>'yes',
'number'=>2
);
//Sendarequesttoexample.com
$result=post_request('http://www.example.com/',$post_data);
if($result['status']=='ok'){
//Printheaders
echo$result['header'];
echo'<hr/>';
//printtheresultofthewholerequest:
echo$result['content'];
}
else{
echo'Aerroroccured:'.$result['error'];
}
希望本文所述对大家的php程序设计有所帮助。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下