PHP Tunnel Proxy: curl / Guzzle / Stream Three Implementations
PHP curl, Guzzle, and Stream Context integrating 16Yun Crawler Proxy.
16Yun Engineering TeamMay 7, 20261 min read
PHP cURL
PHP 的 cURL 扩展通过 CURLOPT_PROXY 参数配置代理:
$host = getenv('PROXY_HOST') ?: 't.16yun.cn';
$port = getenv('PROXY_PORT') ?: '31111';
$user = getenv('PROXY_USERNAME') ?: 'user';
$pass = getenv('PROXY_PASSWORD') ?: 'password';
$tunnel = getenv('PROXY_TUNNEL') ?: 'php-curl-demo';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://httpbin.org/ip');
curl_setopt($ch, CURLOPT_PROXY, $host);
curl_setopt($ch, CURLOPT_PROXYPORT, intval($port));
curl_setopt($ch, CURLOPT_PROXYUSERPWD, "$user:$pass");
curl_setopt($ch, CURLOPT_PROXYHEADER, ["Proxy-Tunnel: $tunnel"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$data = curl_exec($ch);
if ($data === false) {
echo 'curl error: ' . curl_error($ch);
}
curl_close($ch);
echo $data;
| 场景 | cURL 实现 |
|---|---|
| A:强制切换 | 每次 curl_init + CURLOPT_FORBID_REUSE |
| B:保持 IP | 复用 curl handle |
| C-HTTP:Proxy-Tunnel | CURLOPT_PROXYHEADER + Proxy-Tunnel |
| C-HTTPS:Proxy-Tunnel | CURLOPT_PROXYHEADER 在 CONNECT 阶段发送 |
Guzzle
Guzzle 通过 proxy 参数和 curl 选项配置:
use GuzzleHttp\Client;
$client = new Client([
'proxy' => "http://$user:$pass@$host:$port",
'curl' => [
CURLOPT_PROXYHEADER => ["Proxy-Tunnel: $tunnel"],
],
'timeout' => 15,
'verify' => false,
]);
$resp = $client->get('https://httpbin.org/ip');
echo $resp->getBody();
Stream Context
PHP 原生 stream 上下文,零依赖:
$proxy = "tcp://$host:$port";
$auth = base64_encode("$user:$pass");
$opts = [
'http' => [
'proxy' => $proxy,
'header' => [
"Proxy-Authorization: Basic $auth",
"Proxy-Tunnel: $tunnel",
],
'timeout' => 15,
],
];
$context = stream_context_create($opts);
echo file_get_contents('http://httpbin.org/ip', false, $context);
Stream Context 仅支持 HTTP 目标。HTTPS 需要
http://wrapper 配合tcp://代理地址。
三种方案对比
| 方案 | 依赖 | HTTPS | HTTPS Tunnel | 复杂度 |
|---|---|---|---|---|
| cURL | ext-curl | ✅ | ✅ | 低 |
| Guzzle | composer require guzzlehttp/guzzle | ✅ | ✅ | 低 |
| Stream | 无 | ⚠️ 需配置 | ❌ | 中 |
Need an enterprise proxy plan?
We can tailor architecture to your target domains, concurrency, and reliability goals.