Php伪造搜索引擎蜘蛛进行采集

$ctx = stream_context_create(array(
'http' => array(
'timeout' => 5,
'header'=>"User-Agent: Baiduspider+(+http://www.baidu.com/search/spider.htm)\r\n" .
// "Cookie: foo=bar\r\n"
// 'HTTP_REFERER' =>'http://ww.com/index.php',
// 'User-Agent' =>'jongin'
)
)
);
$rs = file_get_contents('http://test.com/test.php', 0, $ctx);


经过分析日志和对比表明和蜘蛛除了ip不同外,是一模一样的...
先了解一下PHP file_get_contents() 函数
定义和用法
file_get_contents() 函数把整个文件读入一个字符串中。
和 file() 一样,不同的是 file_get_contents() 把文件读入一个字符串。
file_get_contents() 函数是用于将文件的内容读入到一个字符串中的首选方法。如果操作系统支持,还会使用内存映射技术来增强性能。
语法
file_get_contents(path,include_path,context,start,max_length)参数 描述
path 必需。规定要读取的文件。
include_path 可选。如果也想在 include_path 中搜寻文件的话,可以将该参数设为 "1"。
context 可选。规定文件句柄的环境。
context 是一套可以修改流的行为的选项。若使用 null,则忽略。
start 可选。规定在文件中开始读取的位置。该参数是 PHP 5.1 新加的。
max_length 可选。规定读取的字节数。该参数是 PHP 5.1 新加的。
说明
对 context 的支持是 PHP 5.0.0 添加的。
针对超时或页面过慢,一般可采取两个解决方案:
1. 利用file_get_contents()第三个参数
PHP代码

<?php
$url = "http://www.1bo8.cn/zhoz.php";
$ctx = stream_context_create(array(
'http' => array('timeout' => 10)
)
);
$result = @<b style="color:black;background-color:#ffff66">file_get_contents</b>($url, 0, $ctx);
if($result){
var_dump($result);
}else{
echo " Buffer is empty";
}
?>
此方法1,我经测试在本地反映良好,但如果在外网测试(环境:中国→美国服务器间)基本都是超时的情况。
测试了TimeOut基本没有用了,建议以下方式。
2. 使用curl扩展库
PHP代码

<?php
$url = "http://www.1bo8.cn/zhoz.php";

try {
echo date('Y-m-d h:i:s');
echo "";
//$buffer = <b style="color:black;background-color:#ffff66">file_get_contents</b>($url);
$buffer = zhoz_get_contents($url);
echo date('Y-m-d h:i:s');
if(emptyempty($buffer)) {
echo " Buffer is empty";
} else {
echo " Buffer is not empty";
}
} catch(Exception $e) {
echo "error ";
}

function zhoz_get_contents($url, $second = 5) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_TIMEOUT,$second);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);

$content = curl_exec($ch);
curl_close($ch);
return $content;
}
?>
综述,根据系统环境来选择到底应用哪种方法:
PHP代码

<?php
function vita_get_url_content($url) {
if(function_exists('<b style="color:black;background-color:#ffff66">file_get_contents</b>')) {
$file_contents = <b style="color:black;background-color:#ffff66">file_get_contents</b>($url);
} else {
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
}
return $file_contents;
}
?>  



上一篇: 关于IIS7.0出错的解决方案
下一篇: Asp防刷新代码
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: php file_get_contents
相关日志:
评论: 0 | 引用: 0 | 查看次数: 2625
发表评论
昵 称:
密 码: 游客发言不需要密码.
邮 箱: 邮件地址支持Gravatar头像,邮箱地址不会公开.
网 址: 输入网址便于回访.
内 容:
验证码:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭

 广告位

↑返回顶部↑