使用php实现反代
使用 PHP 实现反向代理
PHP 可以通过 cURL 或 file_get_contents 实现简单的反向代理功能。以下是两种常见方法:
使用 cURL 实现反向代理
<?php
$targetUrl = 'https://目标网站.com/path';
$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_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
header("Content-Type: $contentType");
echo $response;
curl_close($ch);
?>
使用 file_get_contents 实现简单反代
<?php
$targetUrl = 'https://目标网站.com/path';
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => "Accept-language: en\r\n"
],
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false
]
]);
$content = file_get_contents($targetUrl, false, $context);
foreach ($http_response_header as $header) {
if (strpos($header, 'Content-Type:') === 0) {
header($header);
}
}
echo $content;
?>
处理 POST 请求的反向代理
<?php
$targetUrl = 'https://目标网站.com/api';
$postData = $_POST;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $targetUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
header("Content-Type: $contentType");
echo $response;
curl_close($ch);
?>
处理请求头传递
<?php
$targetUrl = 'https://目标网站.com/path';
$headers = [];
foreach (getallheaders() as $name => $value) {
if (!in_array(strtolower($name), ['host', 'connection'])) {
$headers[] = "$name: $value";
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $targetUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
header("Content-Type: $contentType");
echo $response;
curl_close($ch);
?>
注意事项
-
性能考虑:PHP 实现的反向代理性能不如 Nginx 或 Apache 等专业服务器软件
-
安全性:需要验证目标 URL,防止 SSRF 攻击
-
大文件处理:对于大文件传输,建议使用流式处理
-
缓存策略:可以考虑添加缓存机制提高性能
-
超时设置:建议设置合理的超时时间

curl_setopt($ch, CURLOPT_TIMEOUT, 30);
- 错误处理:应该添加适当的错误处理逻辑
if ($response === false) {
header('HTTP/1.1 502 Bad Gateway');
echo 'Proxy Error: ' . curl_error($ch);
}






