当前位置: 首页 > 科技观察

PHP:发送GET和POST请求的6种方式_0

时间:2023-03-16 23:46:43 科技观察

在i94web的博客中,我尝试了两个社交评论框,畅言和多多,但还是放弃了畅言,不安全。不管是畅所欲言还是多多发言,我都需要远程抓取文章的评论数存入本地数据库。对于多说,请求的格式如下://获取评论数,参数为文章IDfunctiongetCommCount($postid){$jsondata=file_get_contents("http://api.duoshuo.com/threads/counts.json?short_name=i94web&threads=$postid");//设置true返回一个数组,不设置或false返回一个对象$resjson=json_decode($json_decode($jsondata,true);return$resjson['response'][$postid]['comments'];}对于远程请求,方法有很多种,今天LZ收集了六种,供大家参考。1.使用file_get_contents通过get方法获取内容:2.打开urlwithfopen,获取$fp=fopen($url,'r');stream_get_meta_data($fp);while(!feof($fp)){$result.=fgets($fp,1024);}echo"urlbody:$结果";fclose($fp);3.使用file_get_contents通过post获取内容:$data=array('foo'=>'bar');$data=http_build_query($data);$opts=array('http'=>array('method'=>'POST','header'=>"Content-type:application/x-www-form-urlencodedrn".'Content-Length:'.strlen($data).'rn','content'=>$data));$context=stream_context_create($opts);$html=file_get_contents('http://localhost/e/admin/test.html',false,$context);回声$html;4、使用fsockopen函数打开url,获取完整的数据,包括header和body,fsockopen需要PHP.ini中的allow_url_fopen选项开启函数get_url($url,$cookie=false){$url=parse_url($url);$query=$url[path].'?'.$url[query];echo'Query:'.$query;$fp=fsockopen($url[host],$url[port]?$url[端口]:80,$errno,$errstr,30);if(!$fp){returnfalse;}else{$request='GET$queryHTTP/1.1rn';$request.='Host:$url[host]rn';$request.='Connection:Closern';if($cookie)$request.='Cookie:$cookie';$request.='rn';fwrite($fp,$request);while(!@feof($fp)){$result.=@fgets($fp,1024);}fclose($fp);return$result;}}//获取url的html部分,去掉header函数GetUrlHTML($url,$cookie=false){$rowdata=get_url($url,$cookie);if($rowdata){$body=stristr($rowdata,'rnrn');$body=substr($body,4,strlen($body));return$body;}returnfalse;}5.使用fsockopen函数打开url并通过POST获取完整的数据,包括header和body函数=='')//ifnotgivenusethisscriptasreferrer$referrer='111';//makingstringfrom$dataforeach($dataas$key=>$value)$values[]='$key='.urlencode($value);$data_string=implode('&',$values);//找出需要哪个端口——如果没有给出使用标准(=80)if(!isset($URL_Info['port']))$URL_Info['port']=80;//buildingPOST-request:$request.="POST".$URL_Info['path']."HTTP/1.1n";$request.="Host:".$URL_Info['host']."n";$request.="Referer:$referern";$request.="Content-type:application/x-www-form-urlencodedn";$request.='Content-length:'.strlen($data_string)."n";$request.='Connection:close';$request.='Cookie:$cookie';$request.='n';$request.=$data_string.'n';$fp=fsockopen($URL_Info['host'],$URL_Info['port']);fputs($fp,$request);while(!feof($fp)){$result.=fgets($fp,1024);}fclose($fp);return$result;}6.使用curl库,在使用curl库之前,可能需要检查php.ini中是否开启了curl扩展$ch=curl_init();$timeout=5;curl_setopt($ch,CURLOPT_URL,'http://www.ido321.com/');curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);$file_contents=curl_exec($ch);curl_close($ch);echo$file_contents;