好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

file_get_contents防采集解决fsockopen函数

使用fsockopen函数采集网页内容,首先要确认你的php开发环境是不是开启了fsockopen函数,如果未开启的话,就需要先开启了。那么服务器该如何开启php的fsockopen函数呢?

 

对于windows用户:

 

第一步:

php.ini文件中查找

allow_url_fopen = On

使其值为On

 

第二步:

php.ini文件中查找

extension=php_openssl.dll

如果前面有分号,去掉分号

 

第三步:

重启web服务器,apache或IIS即可。

 

对于linux用户:

 

第一步:

vi php.ini

找到 allow_url_fopen 这个参数设置成 On,即

allow_url_fopen = On

 

 

第二步:

让你的php支持 opensll扩展。

默认,是没有openssl扩展的,只能重新编译安装。

yum install openssl openssl-devel

cd /usr/local/src/php-5.2.14/ext/openssl

/usr/local/php/bin/phpize

./configure –with-openssl –with-php-config=/usr/local/bin/php-config

make && make install

看提示,把编译成的openssl.so 拷贝到你在php.ini 中指定的 extension_dir 下

 

第三步:

vi php.ini

加入

extension=openssl.so

第三步:

 

第三步:

重启web server

 

fsockopen 完美采集网页内容(反防采集)代码实例如下:

<?php /**  *  * @param $url     网址  * @param $Referer 来路设置  * @param $timeout 链接超时时长  */ function _sockget($url,$Referer=1,$timeout=5){  $info = parse_url($url);  $fp = fsockopen($info['host'], 80, &$errno, &$errstr, $timeout); if(!$fp) { die('无法连接');                //echo "$errstr ($errno)<br>\n"; } else { //stream_set_blocking($fp,0);//开启非阻塞模式  stream_set_timeout($fp, 5);  //读取超时 $end = "\r\n";          $head = "GET ".$info['path'].($info["query"]?'?'.$info['query']:'')." HTTP/1.1$end"; $head .= "Host: ".$info['host']."$end"; //伪造来路页面 $head .= "Referer: http://".$info['host'].($Referer!=1?$info['path'].($info["query"]?'?'.$info['query']:''):'')."$end"; $head.="User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)$end"; $head .= "Connection: Close$end"; $head .= "$end"; //    echo $head; //    exit; fputs($fp,$head); $info = stream_get_meta_data($fp);//获取读取内容是否超时   if ($info['timed_out']) {    fclose($fp);                   echo 'Connection timed out!';                   die('发送数据超时');               }        $content='';                 while(!feof($fp) && (!$info['timed_out'])) {                 $content.=fgets($fp,1024);                 $info = stream_get_meta_data($fp);                 flush();          }         fclose($fp);         if ($info['timed_out']) {         die('读取数据 Connection timed out!');      }         return $content;       } } //使用方法: $filecontent=_sockget('http://www.bgpy.net/bowenguangshi/aimei_2251.html'); echo  $filecontent; ?>

如果没有权限启用该函数,那么用其他函数代替,如stream_socket_client()。 注意:stream_socket_client()和fsockopen()的参数不同。

$fp = fsockopen($host, $port, $errno, $errstr, $connection_timeout); 修改后: $fp = stream_socket_client("tcp://".$host.":".$port, $errno, $errstr, $connection_timeout);

查看更多关于file_get_contents防采集解决fsockopen函数的详细内容...

  阅读:47次