PHP 爬虫代理示例

阅读模式

代码示例说明

  1. 代码样例不能直接运行,请替换成您自己的代理信息。
  2. 在不同编程语言的代码示例中,需注意其环境版本。
  3. 示例代码使用遇到问题请,我们会为您提供技术支持。
1
<?php
2
// 要访问的目标页面
3
$url = "http://httpbin.org/ip";
4
$urls = "https://httpbin.org/ip";
5
6
// 代理服务器(产品官网 www.16yun.cn)
7
define("PROXY_SERVER", "tcp://t.16yun.cn:31111");
8
9
// 代理身份信息
10
define("PROXY_USER", "username");
11
define("PROXY_PASS", "password");
12
13
$proxyAuth = base64_encode(PROXY_USER . ":" . PROXY_PASS);
14
15
// 设置 Proxy tunnel
16
$tunnel = rand(1,10000);
17
18
$headers = implode("\r\n", [
19
"Proxy-Authorization: Basic {$proxyAuth}",
20
"Proxy-Tunnel: ${tunnel}",
21
]);
22
$sniServer = parse_url($urls, PHP_URL_HOST);
23
$options = [
24
"http" => [
25
"proxy" => PROXY_SERVER,
26
"header" => $headers,
27
"method" => "GET",
28
'request_fulluri' => true,
29
],
30
'ssl' => array(
31
'SNI_enabled' => true, // Disable SNI for https over http proxies
32
'SNI_server_name' => $sniServer
33
)
34
];
35
print($url);
36
$context = stream_context_create($options);
37
$result = file_get_contents($url, false, $context);
38
var_dump($result);
39
40
// 访问 HTTPS 页面
41
print($urls);
42
$context = stream_context_create($options);
43
$result = file_get_contents($urls, false, $context);
44
var_dump($result);
45
?>