PHP API代理示例

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

file_get_contents + stream 上游代理

<?php
    $apiUrl = 'http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json';

    $json = file_get_contents($apiUrl);
    if ($json === false) {
        die('API 请求失败');
    }
    $arr = json_decode($json, true);
    if (!is_array($arr) || count($arr) === 0) {
        die('API 返回为空');
    }
    $ip = $arr[0]['ip'];
    $port = $arr[0]['port'];

    $proxy = "tcp://{$ip}:{$port}";
    $opts = [
        'http' => [
            'proxy' => $proxy,
            'method' => 'GET',
            'request_fulluri' => true,
            'timeout' => 10,
        ],
    ];
    $ctx = stream_context_create($opts);
    $result = file_get_contents('https://httpbin.org/ip', false, $ctx);
    var_dump($result);
?>

curl

<?php
    $apiUrl = 'http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json';
    $json = file_get_contents($apiUrl);
    $arr = json_decode($json, true);
    $ip = $arr[0]['ip'];
    $port = $arr[0]['port'];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://httpbin.org/ip');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_PROXY, $ip);
    curl_setopt($ch, CURLOPT_PROXYPORT, $port);
    curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $data = curl_exec($ch);
    curl_close($ch);
    echo $data;
?>