• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

php中使用Curl、socket、file_get_contents三种方法POST提交数据_php技巧

php 搞代码 3年前 (2022-01-26) 28次浏览 已收录 0个评论

抓取远程内容,之前一直都在用file_get_content函数,其实早就知道有curl这么一个好东西的存在,但是看了一眼后感觉使用颇有些复杂,没有file_get_content那么简单,再就是需求也不大,所以没有学习使用curl。
直到最近,要做一个网页小偷程序的时候才发现file_get_content已经完全不能满足需求了。我觉得,在读取远程内容的时候,file_get_content除了使用比curl便捷以外,其他都没有curl好。

php中curl和file_get_content的一些比较

主要区别:

学习才发现,curl支持很多协议,有FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE以及LDAP,也就是说,它能做到很多file_get_content做不到的事情。curl在php可以实现远程获取和采集内容;实现PHP网页版的FTP上传下载;实现模拟登陆;实现接口对接(API),数据传输;实现模拟Cookie;下载文件断点续传等等,功能十分强大。

了解curl一些基本的使用后,才发现其实并不难,只不过记住里面一些设置参数,难弄一点,但是我们记住几个常用的就可以了。

开启curl:

因为PHP默认是不支持curl功能的,因此如果要用curl的话,首先需要在php.ini中开启该功能,即去掉 ;extension= php_curl.dll 前面的分号,然后保存后重启apache/iis就好了。

基本语法:

$my_curl = curl_init();    //初始化一个curl对象<BR>curl_setopt($my_curl, CURLOPT_URL, "http://www.gaodaima.com");    //设置你需要抓取的URL<BR>curl_setopt($my_curl,CURLOPT_RETURNTRANSFER,1);    //设置是将结果保存到字符串中还是输出到屏幕上,1表示将结果保存到字符串<BR>$str = curl_exec($curl);    //执行请求<BR>echo $str;    //输出抓取的结果<BR>curl_close($curl);    //关闭url请求<BR>

最近需要获取别人网站上的音乐数据。用了file_get_contents函数,但是总是会遇到获取失败的问题,尽管按照手册中的例子设置了超时,可多数时候不会奏效:

$config[‘context’] = stream_context_create(array(‘http’ => array(‘method’ => “GET”,
‘timeout’ => 5//这个超时时间不稳定,经常不奏效
)
));

这时候,看一下服务器的连接池,会发现一堆类似的错误,让我头疼万分:
file_get_contents(http://***): failed to open stream…

现在改用了curl库,写了一个函数替换:
function curl_file_get_contents($durl){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $durl);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$r = curl_exec($ch);
curl_close($ch);
return $r;
}

如此,除了真正的网络问题外,没再出现任何问题。
这是别人做过的关于curl和file_get_contents的测试:
file_get_contents抓取google.com需用秒数:

2.31319094
2.30374217
2.21512604
3.30553889
2.30124092

curl使用的时间:

0.68719101
0.64675593
0.64326
0.81983113
0.63956594

差距很大?呵呵,从我使用的经验来说,这两个工具不只是速度有差异,稳定性也相差很大。

建议对网络数据抓取稳定性要求比较高的朋友使用上面的 curl_file_get_contents函数,不但稳定速度快,还能假冒浏览器欺骗目标地址哦!

方法1: 用file_get_contents 以get方式获取内容

<?php<BR>$url='http://www.domain.com/';<BR>$html = file_get_contents($url);<BR>echo $html;<BR>?><BR>

方法2: 用fopen打开url, 以get方式获取内容

<?php<BR>$fp = fopen($url, 'r'<mark style="color:transparent">来4源gaodaimacom搞#代%码*网</mark><code>搞代gaodaima码</code>);<BR>stream_get_meta_data($fp);<BR>while(!feof($fp)) {<BR>$result .= fgets($fp, 1024);<BR>}<BR>echo "url body: $result";<BR>fclose($fp);<BR>?><BR>

方法3:用file_get_contents函数,以post方式获取url

<?php<BR>$data = array ('foo' => 'bar');<BR>$data = http_build_query($data);</P><P>$opts = array (<BR>'http' => array (<BR>'method' => 'POST',<BR>'header'=> "Content-type: application/x-www-form-urlencodedrn" .<BR>"Content-Length: " . strlen($data) . "rn",<BR>'content' => $data<BR>)<BR>);<BR>$context = stream_context_create($opts);<BR>$html = file_get_contents('http://localhost/e/admin/test.html', false, $context);<BR>echo $html;<BR>?><BR>

方法4:用fsockopen函数打开url,以get方式获取完整的数据,包括header和body

<?php<BR>function get_url ($url,$cookie=false)<BR>{<BR>$url = parse_url($url);<BR>$query = $url[path]."?".$url[query];<BR>echo "Query:".$query;<BR>$fp = fsockopen( $url[host], $url[port]?$url[port]:80 , $errno, $errstr, 30);<BR>if (!$fp) {<BR>return false;<BR>} else {<BR>$request = "GET $query HTTP/1.1rn";<BR>$request .= "Host: $url[host]rn";<BR>$request .= "Connection: Closern";<BR>if($cookie) $request.="Cookie: $cookien";<BR>$request.="rn";<BR>fwrite($fp,$request);<BR>while()) {<BR>$result .= @fgets($fp, 1024);<BR>}<BR>fclose($fp);<BR>return $result;<BR>}<BR>}<BR>//获取url的html部分,去掉header<BR>function GetUrlHTML($url,$cookie=false)<BR>{<BR>$rowdata = get_url($url,$cookie);<BR>if($rowdata)<BR>{<BR>$body= stristr($rowdata,"rnrn");<BR>$body=substr($body,4,strlen($body));<BR>return $body;<BR>}<BR>return false;<BR>}<BR>?><BR>

方法5:用fsockopen函数打开url,以POST方式获取完整的数据,包括header和body

<?php<BR>function HTTP_Post($URL,$data,$cookie, $referrer="")<BR>{<BR>// parsing the given URL<BR>$URL_Info=parse_url($URL);</P><P>// Building referrer<BR>if($referrer=="") // if not given use this script as referrer<BR>$referrer="111″;</P><P>// making string from $data<BR>foreach($data as $key=>$value)<BR>$values[]="$key=".urlencode($value);<BR>$data_string=implode("&",$values);</P><P>// Find out which port is needed – if not given use standard (=80)<BR>if(!isset($URL_Info["port"]))<BR>$URL_Info["port"]=80;</P><P>// building POST-request:<BR>$request.="POST ".$URL_Info["path"]." HTTP/1.1n";<BR>$request.="Host: ".$URL_Info["host"]."n";<BR>$request.="Referer: $referern";<BR>$request.="Content-type: application/x-www-form-urlencodedn";<BR>$request.="Content-length: ".strlen($data_string)."n";<BR>$request.="Connection: closen";</P><P>$request.="Cookie: $cookien";</P><P>$request.="n";<BR>$request.=$data_string."n";</P><P>$fp = fsockopen($URL_Info["host"],$URL_Info["port"]);<BR>fputs($fp, $request);<BR>while(!feof($fp)) {<BR>$result .= fgets($fp, 1024);<BR>}<BR>fclose($fp);</P><P>return $result;<BR>}<BR>?><BR>

方法6:使用curl库,使用curl库之前,可能需要查看一下php.ini是否已经打开了curl扩展

<?php<BR>$ch = curl_init();<BR>$timeout = 5;<BR>curl_setopt ($ch, CURLOPT_URL, 'http://www.domain.com/');<BR>curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);<BR>curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);<BR>$file_contents = curl_exec($ch);<BR>curl_close($ch);<BR>echo $file_contents;<BR>?><BR>

php中 curl, fsockopen ,file_get_contents 三个函数 都可以实现采集模拟发言 。三者有什么区别,或者讲究么

赵永斌:
有些时候用file_get_contents()调用外部文件,容易超时报错。换成curl后就可以.具体原因不清楚
curl 效率比file_get_contents()和fsockopen()高一些,原因是CURL会自动对DNS信息进行缓存(亮点啊有我待亲测)

范佳鹏:
file_get_contents curl fsockopen
在当前所请求环境下选择性操作,没有一概而论:
具我们公司开发KBI应用来看:
刚开始采用:file_get_contents
后来采用:fsockopen
最后到至今采用:curl

(远程)我个人理解到的表述如下(不对请指出,不到位请补充)
file_get_contents 需要php.ini里开启allow_url_fopen,请求http时,使用的是http_fopen_wrapper,不会keeplive.curl是可以的。
file_get_contents()单个执行效率高,返回没有头的信息。
这个是读取一般文件的时候并没有什么问题,但是在读取远程问题的时候就会出现问题。
如果是要打一个持续连接,多次请求多个页面。那么file_get_contents和fopen就会出问题。
取得的内容也可能会不对。所以做一些类似采集工作的时候,肯定就有问题了。
sock较底层,配置麻烦,不易操作。 返回完整信息。

潘少宁-腾讯:
file_get_contents 虽然可以获得某URL的内容,但不能post get啊。
curl 则可以post和get啊。还可以获得head信息
而socket则更底层。可以设置基于UDP或是TCP协议去交互
file_get_contents 和 curl 能干的,socket都能干。
socket能干的,curl 就不一定能干了
file_get_contents 更多的时候 只是去拉取数据。效率比较高 也比较简单。
赵的情况这个我也遇到过,我通过CURL设置host 就OK了。 这和网络环境有关系

 <BR><?php <BR>/** <BR>* Socket版本 <BR>* 使用方法: <BR>* $post_string = "app=socket&version=beta"; <BR>* request_by_socket('jb51.net','/restServer.php',$post_string); <BR>*/ <BR>function request_by_socket($remote_server,$remote_path,$post_string,$port = 80,$timeout = 30){ <BR>$socket = fsockopen($remote_server,$port,$errno,$errstr,$timeout); <BR>if (!$socket) die("$errstr($errno)"); <BR>fwrite($socket,"POST $remote_path HTTP/1.0"); <BR>fwrite($socket,"User-Agent: Socket Example"); <BR>fwrite($socket,"HOST: $remote_server"); <BR>fwrite($socket,"Content-type: application/x-www-form-urlencoded"); <BR>fwrite($socket,"Content-length: ".strlen($post_string)+8.""); <BR>fwrite($socket,"Accept:*/*"); <BR>fwrite($socket,""); <BR>fwrite($socket,"mypost=$post_string"); <BR>fwrite($socket,""); <BR>$header = ""; <BR>while ($str = trim(fgets($socket,4096))) { <BR>$header.=$str; <BR>} <BR>$data = ""; <BR>while (!feof($socket)) { <BR>$data .= fgets($socket,4096); <BR>} <BR>return $data; <BR>} <BR>/** <BR>* Curl版本 <BR>* 使用方法: <BR>* $post_string = "app=request&version=beta"; <BR>* request_by_curl('http://jb51.net/restServer.php',$post_string); <BR>*/ <BR>function request_by_curl($remote_server,$post_string){ <BR>$ch = curl_init(); <BR>curl_setopt($ch,CURLOPT_URL,$remote_server); <BR>curl_setopt($ch,CURLOPT_POSTFIELDS,'mypost='.$post_string); <BR>curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); <BR>curl_setopt($ch,CURLOPT_USERAGENT,"Jimmy's CURL Example beta"); <BR>$data = curl_exec($ch); <BR>curl_close($ch); <BR>return $data; <BR>} <BR>/** <BR>* 其它版本 <BR>* 使用方法: <BR>* $post_string = "app=request&version=beta"; <BR>* request_by_other('http://jb51.net/restServer.php',$post_string); <BR>*/ <BR>function request_by_other($remote_server,$post_string){ <BR>$context = array( <BR>'http'=>array( <BR>'method'=>'POST', <BR>'header'=>'Content-type: application/x-www-form-urlencoded'."". <BR>'User-Agent : Jimmy's POST Example beta'."". <BR>'Content-length: '.strlen($post_string)+8, <BR>'content'=>'mypost='.$post_string) <BR>); <BR>$stream_context = stream_context_create($context); <BR>$data = file_get_contents($remote_server,FALSE,$stream_context); <BR>return $data; <BR>} <BR>?> <BR>

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:php中使用Curl、socket、file_get_contents三种方法POST提交数据_php技巧

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址