file_get_contents设置代理抓取页面

设置代理IP采集数据

$context = array( 
    'http' => array( 
        'proxy' => 'http://127.0.0.1:8087',  //这里设置你要使用的代理ip及端口号 
        'request_fulluri' => true, 
    ), 
); 
$context = stream_context_create($context); 
$html = file_get_contents("http://www.example.com/", false, $context); 
echo $html;

设置需要验证的代理IP采集数据

$auth = base64_encode('USER:PASS');   //USER:PASSWORD 这里是代理服务器的账户名及密码 
$context = array( 
    'http' => array( 
        'proxy' => 'http://127.0.0.1:8087',  //这里设置你要使用的代理ip及端口号 
        'request_fulluri' => true, 
        'header' => "Proxy-Authorization: Basic $auth",
    ), 
); 
$context = stream_context_create($context); 
$html = file_get_contents("http://www.example.com/", false, $context); 
echo $html;

扩展

file_get_contents() 以 POST 方式提交数据

通过传入设置数组,来获取一个上下文对象

$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST', #设置请求方法为POST
        'header' => 'Content-type: application/x-www-form-urlencoded',  #通过设置头文件来设置POST数据格式
        'content' => http_build_query($query_info), #用http_build_query()方法将数组拼合成数据字符
        'timeout' => 20 #设置请求的超时时间
    )
));

然后通过file_get_contents进行数据POST方式提交

$html = file_get_contents('http://www.example.com/', false, $context); 

header里还可以这样传入,比如设置useragent

'header'=>"Accept-language: en\r\n" .
              "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1\r\n"

还可以该种方式设置useragent

ini_set('user_agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1');
如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注