PHP API代理示例

阅读模式

流程:请求 API → 解析 JSON → 处理错误 → 使用返回代理访问目标站。

file_get_contents + stream 上游代理

1
<?php
2
$apiUrl = 'http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json';
3
4
$json = file_get_contents($apiUrl);
5
if ($json === false) {
6
die('API 请求失败');
7
}
8
$arr = json_decode($json, true);
9
if (!is_array($arr) || count($arr) === 0) {
10
die('API 返回为空');
11
}
12
$ip = $arr[0]['ip'];
13
$port = $arr[0]['port'];
14
15
$proxy = "tcp://{$ip}:{$port}";
16
$opts = [
17
'http' => [
18
'proxy' => $proxy,
19
'method' => 'GET',
20
'request_fulluri' => true,
21
'timeout' => 10,
22
],
23
];
24
$ctx = stream_context_create($opts);
25
$result = file_get_contents('https://httpbin.org/ip', false, $ctx);
26
var_dump($result);
27
?>

curl

1
<?php
2
$apiUrl = 'http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json';
3
$json = file_get_contents($apiUrl);
4
$arr = json_decode($json, true);
5
$ip = $arr[0]['ip'];
6
$port = $arr[0]['port'];
7
8
$ch = curl_init();
9
curl_setopt($ch, CURLOPT_URL, 'https://httpbin.org/ip');
10
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
11
curl_setopt($ch, CURLOPT_PROXY, $ip);
12
curl_setopt($ch, CURLOPT_PROXYPORT, $port);
13
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
14
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
15
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
16
$data = curl_exec($ch);
17
curl_close($ch);
18
echo $data;
19
?>