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程序设计有所帮助。