php实现http代理
PHP 实现 HTTP 代理
在 PHP 中实现 HTTP 代理可以通过多种方式完成,以下是一个简单的实现方法:
1. 使用 cURL 实现 HTTP 代理
<?php
$targetUrl = $_GET['url'] ?? '';
if (empty($targetUrl)) {
die('URL parameter is required');
}
$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, false);
// 如果需要设置代理服务器
// curl_setopt($ch, CURLOPT_PROXY, 'proxy.example.com:8080');
// curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'username:password');
$response = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
header("Content-Type: $contentType");
echo $response;
curl_close($ch);
?>
2. 使用 PHP 流处理实现

<?php
$targetUrl = $_GET['url'] ?? '';
if (empty($targetUrl)) {
die('URL parameter is required');
}
$context = stream_context_create([
'http' => [
'method' => $_SERVER['REQUEST_METHOD'],
'header' => getallheaders(),
'follow_location' => 1,
'ignore_errors' => true
]
]);
$response = file_get_contents($targetUrl, false, $context);
foreach ($http_response_header as $header) {
header($header);
}
echo $response;
?>
3. 处理 POST 请求
如果需要处理 POST 请求,可以修改代码:

<?php
$targetUrl = $_GET['url'] ?? '';
if (empty($targetUrl)) {
die('URL parameter is required');
}
$postData = file_get_contents('php://input');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $targetUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$headers = [];
foreach (getallheaders() as $name => $value) {
$headers[] = "$name: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
header("Content-Type: $contentType");
echo $response;
curl_close($ch);
?>
4. 安全注意事项
- 验证输入 URL,防止 SSRF 攻击
- 限制可以访问的域名或 IP 范围
- 考虑添加身份验证机制
- 记录日志以监控使用情况
- 设置适当的超时时间
5. 性能优化
- 使用缓存机制存储常用响应
- 考虑使用 PHP 的 OPcache 加速
- 对于高流量场景,可以考虑使用专门的代理服务器软件
这些方法提供了基本的 HTTP 代理功能,可以根据具体需求进行调整和扩展。






