php实现http代理
PHP 实现 HTTP 代理
使用 cURL 实现简单 HTTP 代理
<?php
$targetUrl = $_GET['url'] ?? '';
if (empty($targetUrl)) {
header('HTTP/1.1 400 Bad Request');
exit('Missing URL parameter');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $targetUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
curl_close($ch);
header_remove();
foreach (explode("\r\n", $headers) as $header) {
if (!empty($header)) {
header($header);
}
}
echo $body;
?>
使用 PHP 内置流处理
<?php
$targetUrl = $_GET['url'] ?? '';
if (empty($targetUrl)) {
header('HTTP/1.1 400 Bad Request');
exit('Missing URL parameter');
}
$context = stream_context_create([
'http' => [
'method' => $_SERVER['REQUEST_METHOD'],
'header' => getallheaders(),
'ignore_errors' => true
]
]);
$response = file_get_contents($targetUrl, false, $context);
foreach ($http_response_header as $header) {
header($header);
}
echo $response;
?>
处理 POST 请求的代理
<?php
$targetUrl = $_GET['url'] ?? '';
if (empty($targetUrl)) {
header('HTTP/1.1 400 Bad Request');
exit('Missing URL parameter');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $targetUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents('php://input'));
}
$headers = [];
foreach (getallheaders() as $name => $value) {
$headers[] = "$name: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
http_response_code($status);
echo $response;
?>
安全性注意事项
- 验证目标 URL 的域名白名单
- 限制可访问的协议(仅允许 http/https)
- 过滤敏感头信息(如 Cookie、Authorization)
- 设置超时限制防止长时间请求
- 记录访问日志用于审计
性能优化建议
- 启用缓存机制减少重复请求
- 使用连接池复用 HTTP 连接
- 压缩传输数据减少带宽消耗
- 异步处理大文件传输
以上代码示例提供了不同复杂度的 PHP HTTP 代理实现方案,可根据实际需求选择适合的方法并添加必要的安全措施。







